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

标签 tsql insert bulk

我有两张 table 。一个叫做@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 值为空,而第三列为空;其余 8 个都填充了所有三列。最终结果应该有 8 行而不是 16 行。

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

那么如何更改此 TSQL 以在不插入新行的情况下更新 @tempImportedData.engine_id?

最佳答案

您需要另一个表变量( @temp )来捕获插入的输出,然后使用 @temp 运行更新语句。反对 @tempImportedData加入 c1c2 .这需要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
; 

关于TSQL批量插入数据,同时将创建的ID返回到原始表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6281727/

相关文章:

UITableView 行异步加载

c++ - 实现批量记录获取

sql - 恢复未保存的 SQL 查询脚本

sql-server - SQL Server 中使用另一个表的内容进行字符串替换(例如 update table1 set value = Replace(table1.value, table2.val1, table2.val2))

java - 在 Play Framework 中使用单个函数插入/更新数据库

php - 1064 : SQL syntax (MySQL INSERT)

.net - 使用Elasticsearch.net或PlainElastic.net批量插入Elasticsearch

c# - mysql存储过程批量插入

sql - Microsoft t sql 如何在用户定义的函数中声明临时变量?

tsql - 如何将 azure SQL 托管实例备份备份到 azure blob