TSQL 中“IDENTITY”的正确使用
可能的重复:
获取插入行标识的最佳方法?
什么时候合适,并且应该如何在 T-SQL 中使用不同的 IDENTITY 关键字?
- SELECT @@IDENTITY,
- SELECT SCOPE_IDENTITY()
- SELECT IDENT_CURRENT('表名')
Possible Duplicate:
Best way to get identity of inserted row?
When is it appropriate and how should someone use the different IDENTITY
key word in T-SQL?
- SELECT @@IDENTITY,
- SELECT SCOPE_IDENTITY()
- SELECT IDENT_CURRENT(‘tablename’)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看一下 SQL SERVER – @@IDENTITY 与 SCOPE_IDENTITY() 与 IDENT_CURRENT – 检索最后插入的记录标识
摘自文章
Have a look at SQL SERVER – @@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT – Retrieve Last Inserted Identity of Record
From the article
MSDN对此有很好的参考。
简而言之,@@IDENTITY 的作用域是服务器上的当前会话(如果例如表上有一个触发器也将 IDENTITY 列添加到表中,那么在 INSERT 后您最终可能会检索到错误的 IDENTITY 值)。
SCOPE_IDENTITY() 将返回当前范围的最后插入的 ID,即不会出现上述问题。
IDENT_CURRENT 不限于任何会话,它返回表级别的信息(跨任何会话为该表生成的最后一个 id)
MSDN has a good reference on this.
In a nutshell, @@IDENTITY's scope is the current session on the server (you could end up retrieving the wrong IDENTITY value after an INSERT if e.g. there is a trigger on the table that also adds to a table with an IDENTITY column).
SCOPE_IDENTITY() will return the last inserted ID for the current scope, i.e. will not give you the problem as outlined above.
IDENT_CURRENT is not limited to any session, it returns info at the table-level (the last id generated for that table across any session)