0

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

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

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

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

除了使用光标或遍历每一行之外,还有哪些选项可以确保跨表拆分的记录之间的关系仍然存在?仅供参考,此插入过程会定期发生,并且可能在两个表中包含多达 1000 多条记录。

4

1 回答 1

2

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

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
于 2012-05-20T12:32:25.177 回答