获取SQL Server 2008中多次插入的标识 [英] Get Identity of multiple insertion in sql server 2008

查看:63
本文介绍了获取SQL Server 2008中多次插入的标识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我将使用一个SQL Server 2008中可用的TSQL一次插入10行. 我想要插入行的标识.我认为以下解决方案可行,但我不确定在运行前一次插入时是否还会发生其他插入操作

Hi
Im going to insert 10 rows in a time using one TSQL which is available in SQL server 2008. I want the IDENTITY of inserted rows. I think the below solution would work but Im not sure if some other insertion happens while im running the previous insertion would affect the result

INSERT INTO tableA VALUES (1,2), (3,4), (4,5), ....
DECLARE @LastID INT = @@IDENTITY
SELECT TOP(10) ID FROM tableA WHERE ID<=@LastID ORDER BY ID DESC

INSERT INTO tableA VALUES (1,2), (3,4), (4,5), ....
DECLARE @LastID INT = @@IDENTITY
SELECT TOP(10) ID FROM tableA WHERE ID<=@LastID ORDER BY ID DESC

推荐答案

只需使用 OUTPUT子句-它可以将输出返回给应用程序,也可以返回到表变量中以进行进一步的工作.

Just use the OUTPUT clause - it can either return output to the application, or into a table variable for further work.

例如您的查询将是:

INSERT INTO tableA
OUTPUT inserted.ID
VALUES (1,2), (3,4), (4,5), ...

这篇关于获取SQL Server 2008中多次插入的标识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆