[英]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
I am trying insert 1 row into an audit table for every row in a temporary table and store the ID of each audit table row in the temporary table. 我正在尝试为临时表中的每一行在审核表中插入1行,并将每个审核表行的ID存储在临时表中。
The columns inserted into the audit table will come from the rows in the temporary table and I will need to refer back to the audit.id via the temporary table (so they need to match correctly) 插入到审核表中的列将来自临时表中的行,我将需要通过临时表返回引用audit.id(因此它们需要正确匹配)
I do not want to use any loops. 我不想使用任何循环。
Without any example tables, data, and desired results, here is my attempt at a solution using output
and a table variable. 没有任何示例表,数据和所需结果,这是我尝试使用
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;
rextester demo: http://rextester.com/JMOT34416 extrester演示: http ://rextester.com/JMOT34416
for the audit
table, returns: 对于
audit
表,返回:
+----+-------+
| id | val |
+----+-------+
| 1 | three |
| 2 | two |
| 3 | one |
+----+-------+
and for the temporary table t
对于临时表
t
+----+-------+----------+
| id | val | audit_id |
+----+-------+----------+
| 1 | three | 1 |
| 2 | two | 2 |
| 3 | one | 3 |
+----+-------+----------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.