开发者

SQL Server list of insert identities

开发者 https://www.devze.com 2023-02-02 17:15 出处:网络
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 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 开发者_如何学Pythonid 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


Use the output clause.

DECLARE @InsertedIDs table(ID int);

INSERT INTO YourTable
    OUTPUT INSERTED.ID
        INTO @InsertedIDs 
    SELECT ...


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消