简体   繁体   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

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.

相关问题 遍历行并在临时表中插入数据-SQL Server 2008 - Iterate through rows and insert data in temp table - SQL Server 2008 无法从SQL Server中的WITH ROWS AS子句插入到临时表中 - Could not insert into temp table from WITH ROWS AS clause in SQL Server 如何在sql中将行从一个临时表插入到另一个 - How to insert rows from one temp table to another in sql 使用 SQL-Server 临时表并将唯一 ID 插入到另一个表中 - Temp table and insert the unique Ids into another table, with SQL-Server 如何从SQL中的多个表向临时表中插入数据 - How to insert data to a temp table from multiple tables in SQL 在SQL2005中使用一条命令将多行插入到临时表中 - Insert multiple rows into temp table with one command in SQL2005 SQL Server-遍历临时表并计算多个值以将行插入第二个表 - SQL Server - loop through temp table and calculate multiple values to insert rows into second table SQL Server将多行合并为一行 - 无临时表 - SQL Server Sum multiple rows into one - no temp table SQL Server:从一百万行中提取域和参数到临时表中 - SQL Server : extract domain and params from 1 million rows into temp table 从多个表中选择行时使用sql server临时表 - using sql server temp table while selecting rows from multiple table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM