繁体   English   中英

SQL-将记录插入多个表和Scope_Identity

[英]SQL - Inserting records into multiple tables, and Scope_Identity

我有一个从多个表派生的临时表,需要将它们插入两个表(T1和T2)中。 T1有一个主键(自动生成),该主键必须作为外键插入到T2中(一对多关系)

我知道我是否使用以下插入语句

INSERT INTO T1 (.....)
SELECT (.....) FROM X

我无法使用scope_identity,因为那样只会给我最后一个自动生成的ID,以便在T2中使用。

除了使用游标或遍历每一行之外,还有哪些选项可用来确保保留跨表分割的记录之间的关系? 仅作为参考,此插入过程定期发生,并且可能在两个表中包含多达1000多个记录。

我认为“输出子句”可以解决您的问题。 一个例子

create table itest ( i int identity not null primary key, j int not null unique )
create table #new ( i int not null, j int not null)
insert into itest (j)
output inserted.i, inserted.j into #new
select o.object_id from sys.objects as o
select * from #new
drop table #new, itest;
go

暂无
暂无

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

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