简体   繁体   中英

PSQL - how to insert data to the altered table?

I have an EMPLOYEE table with foreign key Dno that refers to Dnumber in the DEPARTMENT table. In the DEPARTMENT table there is also foreign key Mgr_ssn that refers to Ssn in EMPLOYEE table.

I created the table using

ALTER TABLE employee 
ADD foreign key (dno) references department(dnumber) 
    on delete restrict on update cascade;

(both Dno and Mgr_ssn are NOT NULL)

But now I am confused how to insert the data, because it always violates referential integrity constraint, any suggestion?

Thank you :)

Foreign keys are usually not given the "not null" constraint. What would you do if there is a new employee who has not been assigned a dept. Or a new dept with no manager.

Still, for your problem you should use the " DEFERRABLE " property of Oracle Constraints. This means, any constraint will be checked at commit point only. Thus you can insert dno and empnos first, commit later. At this point there will be no constraint viokation as the FK exists.

ALTER TABLE employee ADD foreign key (dno) references department(dnumber) INITIALLY DEFERRED DEFERRABLE;

--Do the Same for dept

Then, Insert into emp (...) insert into dept(...) commit;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM