2012-05-20 68 views
0

我有一个从多个表派生而来的临时表,这些表需要插入到两个表(T1和T2)中。 T1有一个主键(自动生成),它必须被插入到T2作为一个外键(其中:很多关系)SQL - 将记录插入到多个表中,并且Scope_Identity

我知道,如果我用下面的INSERT语句

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

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

除了使用光标或通过每行的循环之外,还存在哪些选项,以确保跨表分割的记录之间的关系保持不变?仅供参考,插入过程会定期发生,并且可能在两个表中包含1000多条记录。

+0

看一看[这个问题](http://stackoverflow.com/questions/5365629/using-merge-output-to-get-mapping-between-source-id-and-target -ID)。看起来像你在找什么。 –

回答

3

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

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 
+0

关于这个问题的一个很好的阅读可以在这里找到http://www.simple-talk.com/sql/learn-sql-server/implementing-the-output-clause-in-sql-server-2008/ – buckley

相关问题