我正在使用 ASP.NET 和 SQL Server 构建网站,并且使用
SELECT PK FROM Table WHERE PK = @@identity
我的问题是,使用 @@identity
或使用以下内容来检索多用户网站最后插入的 PK 哪个更好、更可靠:
SELECT MAX(PK) FROM Table WHERE PK = Session ("UserID")
最佳答案
我不确定您到底想要实现什么,但检索连接上最后一个语句的主键值的推荐方法是使用 SCOPE_IDENTITY()
@@Identity 在使用触发器时尤其危险,因为它返回最后生成的标识值,包括由语句中的触发器生成的值。
MSDN有以下几点要说:
SCOPE_IDENTITY and @@IDENTITY return the last identity values that are generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; @@IDENTITY is not limited to a specific scope.
您当然应该使用 SCOPE_IDENTITY() 来支持 MAX(PK) 方法 - 任何数量的 future 可能的更改都可能使该方法无效。
关于asp.net - 使用@@identity检索PK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2036369/