can SQL insert using select return multiple identities? [duplicate]

点点圈 提交于 2019-11-30 01:41:10

问题


I am insertnig into a table using a selection

INSERT california_authors (au_id, au_lname, au_fname)
SELECT au_id, au_lname, au_fname
FROM authors
WHERE State = 'CA'

say i have an identity column in california_authors. Can i get all the ids inserted by the above particular insertion just like i can get @@IDENTITY for last single insertion ?

I can't use select command for california_authors as there may exists previously inserted records with filter State = 'CA'


回答1:


You can use the output clause.

Something like this if your identity column is named `IdentityCol' will return you id's as a result set.

INSERT california_authors (au_id, au_lname, au_fname)
OUTPUT inserted.IdentityCol
SELECT au_id, au_lname, au_fname
FROM authors
WHERE State = 'CA'

You can insert the id's to a table using output ... into.
Here is a sample that stores the id's in a table variable.

declare @IDs table (id int)

INSERT california_authors (au_id, au_lname, au_fname)
OUTPUT inserted.IdentityCol INTO @IDs
SELECT au_id, au_lname, au_fname
FROM authors
WHERE State = 'CA'


来源:https://stackoverflow.com/questions/8982934/can-sql-insert-using-select-return-multiple-identities

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