SQL Server list of insert identities

霸气de小男生 提交于 2019-12-28 13:46:10

问题


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


回答1:


Use the output clause.

DECLARE @InsertedIDs table(ID int);

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



回答2:


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.



来源:https://stackoverflow.com/questions/4619343/sql-server-list-of-insert-identities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!