获取最后插入记录的ID

编程入门 行业动态 更新时间:2024-10-26 18:16:55
本文介绍了获取最后插入记录的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用以下查询向表中插入多条记录:

I'm inserting multiple records to a table using the below query:

INSERT INTO Table1(FirstName, LastName, EmailAddress) SELECT t2.FirstName, t2.LastName, t2.EmailAddress FROM Table2 t2

由于查询插入了多条记录,我无法使用 SCOPE_IDENTITY 来检索 PK.有没有什么方法可以获取最后插入记录的ID?

Since the query is inserting multiple records, I can't use SCOPE_IDENTITY to retrieve PK. Is there any method to get the ID's of last inserted records?

推荐答案

SCOPE_IDENTITY() 将正确地为您提供 LAST ID.您需要的是将它与@@Rowcount 结合起来为您提供 ID 的范围.正如另一位理查德指出的,这仅在您的增量设置为 1 时才有效

SCOPE_IDENTITY() will correctly give you the LAST ID. What you need is to combine it with @@Rowcount to give you the range of IDs. As the other Richard points out, this only works if your increment is set to 1

例如:

declare @last int, @first int insert ... select @last = scope_identity(), @first = scope_identity() - @@rowcount + 1

另一种方法(在 SQL Server 2008 中使用它来保证结果)是使用 OUTPUT 子句

declare @ids table (id int) INSERT INTO Table1 (FirstName ,LastName ,EmailAddress) output inserted.id into @ids -- Get the ids SELECT id from @Ids

该表现在包含所有插入的 id

The table now contains all the inserted ids

更多推荐

获取最后插入记录的ID

本文发布于:2023-10-13 20:44:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1489026.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!