SQL Server list of insert identities

2019-01-18 04:31发布

I have a table with an autoincrement id that I am doing a

INSERT INTO ( ... ) SELECT ... FROM ...

Is there a way for me to get the list of id's that have been inserted?

I was thinking I could get the max id before the insert then after and assuming everything in between is new, but then if a row gets inserted from somewhere else I could run into problems. Is there a proper way to do this?

I am using SQL Server 2005

2条回答
成全新的幸福
2楼-- · 2019-01-18 05:04

Create a table variable and then use the OUTPUT clause into the table variable.

OUTPUT inserted.NameOfYourColumnId INTO tableVariable

Then you can SELECT from your table variable.

查看更多
甜甜的少女心
3楼-- · 2019-01-18 05:20

Use the output clause.

DECLARE @InsertedIDs table(ID int);

INSERT INTO YourTable
    OUTPUT INSERTED.ID
        INTO @InsertedIDs 
    SELECT ...
查看更多
登录 后发表回答