How to insert values into existing SQL Server tabl

2019-03-04 17:56发布

问题:

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.