SQL可以使用select插入返回多个身份吗? [英] can SQL insert using select return multiple identities?
问题描述
我正在使用选择将n插入表格中
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'
说我在california_authors
中有一个标识列.我可以获取上述特定插入内容插入的所有ID吗,就像我可以获取最后一个single insertion
的@@ IDENTITY吗?
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
?
我不能对california_authors
使用选择命令,因为可能存在先前插入的带有过滤器State = 'CA'
的记录
I can't use select command for california_authors
as there may exists previously inserted records with filter State = 'CA'
推荐答案
您可以使用输出子句.
如果您的身份列名为"IdentityCol",则将返回您的ID作为结果集.
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'
您可以使用output ... into
将ID插入表中.
这是一个将id存储在表变量中的示例.
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'
这篇关于SQL可以使用select插入返回多个身份吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!