简体   繁体   中英

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

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

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.

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.

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