【发布时间】:2009-05-01 10:47:37
【问题描述】:
我将一堆新行插入到定义如下的表中:
CREATE TABLE [sometable](
[id] [int] IDENTITY(1,1) NOT NULL,
[someval] sometype NOT NULL
)
使用以下插入:
insert into sometable select somefield as someval from othertable
完成后,我想知道所有新插入的行的 ID。 SCOPE_IDENTITY() 只返回最后插入的行的 ID。
如何获取所有新 ID?
想到的一种方法是从 sometable 和插入后的 scope_identity() 中获取当前最大的标识,并使用这两个值从 sometable 中进行选择。例如:
declare @currentMaxId int;
select @currentMaxId=MAX(id) from sometable
insert into sometable select somefield as someval from othertable
select * from sometable where id>@currentMaxId and id<=SCOPE_IDENTITY()
有更好的模式吗?
【问题讨论】:
标签: sql sql-server insert identity