I am currently running on SQL plus and i have 2 tables.
If i enter values into dept ( nm_employees ) and if that value is not there in dept2 ( nm_departments ), then I have to write a PL in SQL to enter the value in dept2. I have the code written but it is incorrect. any ideas?
CREATE TABLE nm_employees(
name varchar(20),
dept varchar(20),
CONSTRAINT empPK PRIMARY KEY (dept)
);
CREATE TABLE nm_departments(
dept2 varchar(20),
CONSTRAINT departments FOREIGN KEY (dept2) REFERENCES nm_employees(dept)
);
INSERT INTO nm_employees values ('nancy','engineer');
IF NOT EXISTS (SELECT dept FROM nm_employees where dept='engineer'
)
THEN
INSERT INTO nm_departments values ('engineer');
END IF;
First point is that you don’t use the fancy inverted commas for SQL. Use standard single-quotes (
').Second point is that IF..THEN is used only in programming blocks, like triggers. In regular SQL batches, you can use
INSERT...SELECT.You also had the wrong table in the EXISTS test, where you should be checking in nm_departments, not nm_employees.
For what it’s worth, this looks like an exercise, so here are some additional pointers:
Employee [M] ->--|- [1] Department, i.e. employee belongs to one department, each department has many employees