我对 SQL Server 中 SCOPE_IDENTITY() 的文档和行为有点困惑。
本页https://learn.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql?view=sql-server-2017关于 SCOPE_IDENTITY() 是这样说的:
Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, if two statements are in the same stored procedure, function, or batch, they are in the same scope.
它包含这个示例
USE AdventureWorks2012;
GO
INSERT INTO Person.ContactType ([Name]) VALUES ('Assistant to the Manager');
GO
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];
GO
SELECT @@IDENTITY AS [@@IDENTITY];
GO
返回结果
SCOPE_IDENTITY
21
@@IDENTITY
21
从文档中我认为 SCOPE_IDENTITY() 的结果将为 NULL,因为 SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];与 INSERT 命令在不同的批处理中执行(因为它在 GO 之后)...我在这里缺少什么?
最佳答案
我同意,我认为该文档有点误导。 SCOPE_IDENTITY
确实在同一连接上直接执行的多个批处理中保留其值。
但请注意,如果您通过使用字符串执行 EXEC
创建内部批处理,则该内部批处理的 SCOPE_IDENTITY
独立于>您的外部批处理的SCOPE_IDENTITY
此脚本生成值 2
,而不是 5
:
create table T1 (ID int IDENTITY(2,1000) not null,Val char(1))
create table T2 (ID int IDENTITY(5,1000) not null, Val char(1))
go
insert into T1(Val) values ('a')
exec('insert into T2(Val) values (''b'')')
select SCOPE_IDENTITY()
关于sql - 对 SCOPE_IDENTITY() 和 GO 感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50268037/