繁体   English   中英

SQL Server:如何从临时表中插入多行数据,并在临时表中存储插入的行的ID

[英]SQL-Server: How do I insert multiple rows with data from a temp table + store the ID of the inserted rows in the temp table

我正在尝试为临时表中的每一行在审核表中插入1行,并将每个审核表行的ID存储在临时表中。

插入到审核表中的列将来自临时表中的行,我将需要通过临时表返回引用audit.id(因此它们需要正确匹配)

我不想使用任何循环。

没有任何示例表,数据和所需结果,这是我尝试使用output和表变量的解决方案。

create table t (id int not null identity(1,1), val varchar(32), audit_id int null);
insert into t (val) values ('three'),('two'),('one');
create table audit (id int not null identity(1,1), val varchar(32));

/* table variable for output */
declare @output table (id int, val varchar(32));

/* insert with output */
insert into audit (val)
output inserted.id, inserted.val into @output
select val
from t;

/* updated t from output */
update t 
set audit_id = o.id
from t
  inner join @output o
    on t.val = o.val;

select * from audit;
select * from t;

extrester演示: http ://rextester.com/JMOT34416

对于audit表,返回:

+----+-------+
| id |  val  |
+----+-------+
|  1 | three |
|  2 | two   |
|  3 | one   |
+----+-------+

对于临时表t

+----+-------+----------+
| id |  val  | audit_id |
+----+-------+----------+
|  1 | three |        1 |
|  2 | two   |        2 |
|  3 | one   |        3 |
+----+-------+----------+

暂无
暂无

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

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