简体   繁体   English

插入with输出子句

[英]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

i'm stuck with this..i have two join tables and what i want is to copy the same set of data from table1 to itself and copy the new id of the newly copied data from table1 to table2 column id2 by using OUTPUT clause. 我坚持这个..我有two join tables联接two join tables ,我想要的是将同一组数据从table1复制到自身,并使用OUTPUT子句将新复制的数据的新id从table1复制到table2id2

but now with the query above i cant get through the column that i needed..how can i insert column B.title & B.amount to table2 ? 但是现在有了上面的查询,我无法通过所需的列..如何将B.titleB.amount列插入到table2

If table 1 and table 2 have a 1:1 relationship, and no foreign key exists between the two then you could do this in a single statement: 如果表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 SQL小提琴示例

Realistically though, if your tables are related they should have a foreign key, and in most cases they won't be 1:1, rather 1:n. 但是实际上,如果您的表相关,则它们应该具有外键,并且在大多数情况下,它们不是1:1,而是1:n。

In which case you would still need to use MERGE to caputre both the new ID and the old ID, but you would then need to capture this mapping in a temporary table before performing a second insert to Table2: 在这种情况下,您仍然需要使用MERGE来对新ID和旧ID都进行大写,但是随后您需要在执行对Table2的第二次插入之前在临时表中捕获此映射:

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 SQL小提琴示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM