【问题标题】:SQL - Inserting records into multiple tables, and Scope_IdentitySQL - 将记录插入多个表和 Scope_Identity
【发布时间】:2012-05-20 12:28:13
【问题描述】:

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

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

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

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

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

【问题讨论】:

标签: sql sql-server sql-server-2008


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-28
相关资源
最近更新 更多