Insert into with output 子句

Insert into with output clause

INSERT INTO Table1(group, account)

OUTPUT inserted.Id, B.title, B.amount 
INTO Table2(id2, title, amount) 

SELECT A.*,
         B.title,
           B.amount,
            B.id2    
FROM Table1 AS A

LEFT OUTER JOIN
(SELECT  title,
          amount,
           id2
 FROM Table2) AS B
 ON A.id = B.id2

我坚持这个..我有two join tables,我想要的是将同一组数据从table1复制到它自己并复制新复制数据的新ID使用 OUTPUT 子句从 table1table2id2

但现在使用上面的查询我无法通过我需要的列..我如何插入列 B.title & B.amounttable2

如果 table 1 和 table 2 有 1:1 关系,并且两者之间不存在外键,那么你 可以 这在一个声明中:

MERGE Table1 AS a 
USING
(   SELECT  A.[group], A.account, B.title, B.amount, B.id2    
    FROM    Table1 AS A
            LEFT OUTER JOIN Table2 AS B
                ON A.id = B.id2
) AS b
    ON 1 = 0
WHEN NOT MATCHED THEN 
    INSERT ([group], account)
    VALUES (b.[group], b.account)
OUTPUT inserted.Id, B.title, B.amount 
    INTO Table2(id2, title, amount);

Example on SQL Fiddle

但实际上,如果您的 table 是相关的,它们应该有一个外键,并且在大多数情况下它们不会是 1:1,而是 1:n。

在这种情况下,您仍然需要使用 MERGE 来捕获新 ID 和旧 ID,但是您需要在执行之前在临时 table 中捕获此映射第二次插入表 2:

DECLARE @Map TABLE (OldID INT NOT NULL, NewID INT NOT NULL);

MERGE Table1 AS a 
USING
(   SELECT  A.ID, A.[group], A.account  
    FROM    Table1 AS A
) AS b
    ON 1 = 0
WHEN NOT MATCHED THEN 
    INSERT ([group], account)
    VALUES (b.[group], b.account)
OUTPUT inserted.Id, b.ID
    INTO @Map(NewID, OldID);

INSERT Table2 (id2, title, amount)
SELECT  m.NewID, b.title, b.amount
FROM    @Map AS m
        INNER JOIN Table2 AS b
            ON b.ID2 = m.OldID;

Example on SQL Fiddle