次のように定義されているテーブルに新しい行の束を挿入しています。
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を取得するにはどうすればよいですか?
頭に浮かぶ1つの方法は、現在最大のIDをsometableから取得し、scope_identity()を挿入後に取得し、これら2つの値を使用して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()
より良いパターンはありますか?