No way to use TSQL Output with normal foreign key constraints?

前端 未结 4 1864
野的像风
野的像风 2021-01-18 06:30

The following snippet fails with error:

The target table \'dbo.forn\' of the OUTPUT INTO clause cannot be on either side of a (primary key, foreign ke

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-18 06:38

    According to technet

    There is no guarantee that the order in which the changes are applied to the table and the order in which the rows are inserted into the output table or table variable will correspond.

    Based on this there are a number of restrictions, among which is the one you ran into above, but if all you want is to record the inserted value in a second table I don't see why you would need the foreign key relationship you define above.

    If you do need the foreign key relationship you could accomplish the same thing by using a trigger like this.

        IF OBJECT_ID ('dbo.forn') IS NOT NULL
    begin
        alter table dbo.forn drop constraint FK_forn_prim
        DROP TABLE dbo.forn;
    end
    IF OBJECT_ID ('dbo.prim') IS NOT NULL
        DROP TABLE dbo.prim;
    go
    
    CREATE TABLE dbo.prim (c1 int PRIMARY KEY);
    CREATE TABLE dbo.forn (c1 int CONSTRAINT FK_forn_prim FOREIGN KEY (c1) REFERENCES dbo.prim(c1));
    go
    
    CREATE TRIGGER InsertRecord
       ON  dbo.Prim
       AFTER Insert
    AS 
    BEGIN
        SET NOCOUNT ON;
        Insert into dbo.forn Select * from inserted;
    END
    GO
    
    INSERT INTO dbo.prim SELECT 1;
    

提交回复
热议问题