How to insert values into existing SQL Server tables with foreign keys

假装没事ソ 提交于 2019-12-04 05:50:50

问题


I have a database and I want to insert new values to the table, the problem is that I have two tables with FK to each other. I know the problem my be something with the Alter Table, however I can't figure out what cause it.

First table: Department

 CREATE TABLE [dbo].[Department]
 (
    [DID] [int]  primary key,
    [Name] [varchar](255) ,
    [Description] [varchar](255) ,
    [ManagerId] [int]
);

Second table: OfficialEmployee

CREATE TABLE [dbo].[OfficialEmployee]
(
    [EID] [int]  primary key,
    [StartDate] [date] ,
    [Degree] [varchar](255) ,
    [DepartmentId] [int] ,

    CONSTRAINT [FK_DIDOfficial] 
        FOREIGN KEY([EID]) REFERENCES [dbo].[Employee] ([EID]) 
                ON UPDATE CASCADE ON DELETE CASCADE,
    CONSTRAINT [FK_EIDOfficial] 
        FOREIGN KEY([DepartmentId]) REFERENCES [dbo].[Department] ([DID]) 
                ON UPDATE CASCADE ON DELETE CASCADE
);

Alter Table Expression:

ALTER TABLE [dbo].[Department] WITH CHECK 
    ADD CONSTRAINT [FK_DepMan] 
        FOREIGN KEY([ManagerId]) REFERENCES [dbo].[OfficialEmployee] ([EID]) 
                ON DELETE NO ACTION

I just need that some one will tell me how do I insert values to one of the tables

Thank you in advance


回答1:


Given the structure, I think you need two inserts and an update:

  1. Insert a new department with a NULL manager.
  2. Insert the manager in the employees table.
  3. Update the department with the manager's id.



回答2:


Deferred constraint will help solving this case without the need of inserting null value rows. But only Postgresql and Oracle supports this kind of constraint. On using the DEFERRABLE keyword, constraint will be enforced only at the time of transaction commit. Unfortunately sql server is not supporting this constraint.



来源:https://stackoverflow.com/questions/53683392/how-to-insert-values-into-existing-sql-server-tables-with-foreign-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!