插入with输出子句

时间:2018-07-19 09:12:47

标签: sql sql-server 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。通过使用table1子句将{1}}移至table2id2

但是现在有了上面的查询,我无法遍历所需的列。如何将列OUTPUTB.title插入B.amount中?

1 个答案:

答案 0 :(得分:0)

如果表1和表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

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

在这种情况下,您仍然需要使用MERGE来同时对新ID和旧ID进行首字母大写,但是随后您需要在执行对Table2的第二次插入之前在临时表中捕获此映射: / p>

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