SQL INSERT with OUTPUT INSERT

时间:2017-10-24 22:11:32

标签: sql sql-server

我认为我对这个问题有一点兴趣。我尝试了一些不同的东西,它真的不应该是这么复杂。也许有人可以帮助我?

我有一个数据表(源),我需要将其复制到另外两个表(target1和target2)。这些表之间具有FK约束。所以我需要将插入记录的id输出到第二个表中。我得到的最接近的是使用MERGE,但它抱怨说:

  

OUTPUT INTO子句不能位于(主键,外键)的任何一侧   关键)。

欢迎提供以下任何帮助,或者如果我完全走错了路,我将不胜感激任何方向:

BEGIN TRAN;
MERGE [DBTarget].[dbo].[TargetTable1] AS T

USING [DBSource].[dbo].[SourceTable] AS S ON (T.[Col1] = S.[Col1])

WHEN NOT MATCHED BY TARGET

    THEN INSERT([Col1] -- Target column
               ,[Col2] -- Target column
               ,[Col3] -- Target column
               ,[Col4])-- Target column

         VALUES(S.[Col1] -- Source column
               ,(SELECT [Col9] FROM [DBSource2].[dbo].[SourceTable2] YI WHERE YI.[Col1] = S.[Col1]) -- Here i am reaching out to another table for a column value for the inserted row
               ,S.[Col3] -- Source column
               ,S.[Col4])-- Source column

OUTPUT
    inserted.Id -- Value inserted to: [DBTarget].[dbo].[TargetTable2].[Col1]
    ,S.[Col2]   -- Value inserted to: [DBTarget].[dbo].[TargetTable2].[Col2]
    ,S.[Col3]   -- Value inserted to: [DBTarget].[dbo].[TargetTable2].[Col3]
    ,NULL       -- Value inserted to: [DBTarget].[dbo].[TargetTable2].[Col4]

INTO [DBTarget].[dbo].[TargetTable2] ([Col1]
                                     ,[Col2]
                                     ,[Col3]
                                     ,[Col4]);

ROLLBACK TRAN;  
GO 

0 个答案:

没有答案