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

前端 未结 4 1956
野的像风
野的像风 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:50

    You're correct, output statements won't work on tables under foreign key constraints.

    Another option would be to temporarily disable the constraints while you insert the data. Though this shouldn't be the norm, it works well for one time loads of data.

    ALTER TABLE dbo.forn
    NOCHECK CONSTRAINT FK_forn_prim
    GO
    
    INSERT INTO dbo.prim
        OUTPUT inserted.c1 INTO dbo.forn
    SELECT 1;
    
    ALTER TABLE dbo.forn
    CHECK CONSTRAINT FK_forn_prim
    GO
    

提交回复
热议问题