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

zdo*_*OI3 5 t-sql insert bulk

我有两张桌子。一个称为@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 ;
Run Code Online (Sandbox Code Playgroud)

我注释掉了以 OUTPUT 开头的两行。

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

第二个 OUTPUT 语句与第一个 OUTPUT 语句有相同的问题 - 16 行而不是 8 行。但是新的 8 行包含 null、null、engine_id

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

dpm*_*gly 0

@tempImportedData 中仍然保留着旧数据。第一个 OUTPUT 语句似乎在新行中插入了正确的数据,但旧行仍然存在。如果您对 @tempImportedData 运行 DELETE,删除脚本结尾处 engine_id 为 null 的所有行,则应该留下正确的八行。