我正在向一个定义如下的表中插入大量新行:
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()
有更好的设计模式吗?
OUTPUT
而不使用INTO
,并且在使用INTO
时给出错误值)。 解释和可能的解决方法(至少针对UPDATE
情况)列在此处:https://dev59.com/qWYs5IYBdhLWcg3wBvb7 - Alejandro