TSQL批量插入数据,同时将创建的id返回到原始表

我有两张桌子.一个叫做@tempImportedData,另一个叫@tempEngine.

我有@tempImportedData中的数据我想将这些数据放入@tempEngine,一旦插入到@tempEngine中,就会创建一个id.我希望将该id放回相应行中的@tempImportedData.我相信这是OUTPUT声明的目的.我几乎有一份工作副本,请看下面.

Declare @tempEngine as table(
     id int identity(4,1) not null
    ,c1 int
    ,c2 int
);
Declare @tempImportedData as table(
     c1 int
    ,c2 int
    ,engine_id int
);
insert into @tempImportedData  (c1, c2)
    select 1,1
    union all select 1,2
    union all select 1,3
    union all select 1,4
    union all select 2,1
    union all select 2,2
    union all select 2,3
    union all select 2,4
;
INSERT INTO @tempEngine ( c1, c2 ) 
    --OUTPUT INSERTED.c1, INSERTED.c2, INSERTED.id  INTO @tempImportedData (c1, c2, engine_id) --dups with full data
    --OUTPUT INSERTED.id  INTO @tempImportedData (engine_id) -- new rows with wanted data, but nulls for rest
    SELECT 
         c1
        ,c2
    FROM 
        @tempImportedData
;       
select * from @tempEngine ;
select * from @tempImportedData ;

我已经注释掉了以OUTPUT开头的两行.

第一个问题是它将所有正确的数据插入到@tempImportedData中,因此最终结果是存在16行,前8个是相同的,其中engine_id为空值,而第三列为null;其余8个已填充所有三列.最终结果应该是8行而不是16行.

第二个OUTPUT语句与第一个 – 16行而不是8行具有相同的问题.但是,新的8行包含null,null,engine_id

那么如何更改此TSQL以更新@ tempImportedData.engine_id而不插入新行?

最佳答案 您需要另一个表变量(@temp)来捕获插入的输出,然后使用@temp对@tempImportedData连接c1和c2运行更新语句.这要求c1和c2的组合在@tempImportedData中是唯一的.

Declare @temp as table(
     id int
    ,c1 int
    ,c2 int
);

INSERT INTO @tempEngine ( c1, c2 ) 
    OUTPUT INSERTED.id, INSERTED.c1, INSERTED.c2 INTO @temp
    SELECT 
         c1
        ,c2
    FROM 
        @tempImportedData
;       

UPDATE T1
  SET engine_id = T2.id
FROM @tempImportedData as T1
  INNER JOIN @temp as T2
    on T1.c1 = T2.c1 and
       T1.c2 = T2.c2
; 
点赞