使用@@identity检索PK
我正在使用 ASP.NET 和 SQL Server 构建一个网站,我使用
SELECT PK FROM Table WHERE PK = @@identity
我的问题是,使用 @@identity
或使用此来检索多用户网站最后插入的 PK 哪个更好、更可靠:
SELECT MAX(PK) FROM Table WHERE PK = Session ("UserID")
I'm building a website using ASP.NET and SQL Server, and I use
SELECT PK FROM Table WHERE PK = @@identity
My question is which is better and more reliable to retrieve the last inserted PK for multiuser website, using @@identity
or using this:
SELECT MAX(PK) FROM Table WHERE PK = Session ("UserID")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不确定您到底想要实现什么,但检索连接上最后一个语句的主键值的推荐方法是使用 SCOPE_IDENTITY()
@@Identity 在您使用触发器的情况下特别危险,因为它返回最后生成的标识值,包括由语句中的触发器生成的标识值。
MSDN 有以下说法:
您当然应该使用 SCOPE_IDENTITY() 来支持 MAX(PK) 方法 - 任何数量的未来可能的更改都可能使该方法无效。
I'm not sure exactly what you want to achieve, but the recommended way to retrieve the primary key value of the last statement on a connection is to use SCOPE_IDENTITY()
@@Identity is particularly risky where you are using triggers, since it returns the last generated identity value, including those generated by triggers flowing on from a statement.
MSDN has the following to say:
You should certainly use SCOPE_IDENTITY() in favour of the MAX(PK) approach - any number of possible future changes could invalidate this method.
对于 SQL Server 2005 及更高版本...
您可以使用 OUTPUT 子句...
否则,您只能使用 SCOPE_IDENTITY()
For SQL Server 2005 and above...
You can do the INSERT and SELECT in one call using the OUTPUT clause...
Otherwise, you only use SCOPE_IDENTITY()
正如 @David Hall 所提到的,
@@IDENTITY
关键字返回当前连接的最近创建的身份,而不总是查询中最近添加的记录的身份,并且可能返回不正确的值。使用MAX(PK)
出现错误值的可能性更高,我强烈建议不要使用它。为了避免任何竞争条件,我建议您使用 SCOPE_IDENTITY() 来返回 INSERT SQL 语句或存储过程中最近添加的记录的标识。As mentioned by @David Hall the
@@IDENTITY
keyword returns the most recently created identity for your current connection, not always the identity for the recently added record in your query and may return an incorrect value. UsingMAX(PK)
there is a higher chance for an incorrect value and I'd strongly recommend against using it. To avoid the any race conditions I'd suggest that you useSCOPE_IDENTITY()
to return the identity of the recently added record in your INSERT SQL Statement or Stored Procedure.取决于您想要实现的目标。如果您想将刚刚生成的 ID 返回给 ASP.NET 代码(典型场景),那么 @@identity 就是您的朋友。在高并发的情况下,mak(PK)甚至不能保证就是你所追求的PK。
Depends on what you're trying to accomplish. If you want to return the just-generated ID to the ASP.NET code (a typical scenario), then @@identity is your friend. In a high-concurrency situation, mak(PK) is not even guaranteed to be the PK you're after.