CREATE TABLE TestTB1(ID INT IDENTITY(1,1) PRIMARY KEY, DATA VARCHAR(50))
当会话没有插入数据的时候,@@IDENTITY 和 SCOPE_IDENTITY() 都是null,而 IDENT_CURRENT是1 这个是需要区别
SELECT @@identity AS '@@identity' , SCOPE_IDENTITY() AS 'SCOPE_IDENTITY()' , IDENT_CURRENT('TestTB1') AS 'IDENT_CURRENT()'测试@@IDENTITY 和 IDENT_CURRENT('TestTB1') 的值变化是否与会话有关会话1:
1 INSERT INTO TestTB1 (Data) SELECT 'A'2 SELECT '会话1',@@IDENTITY AS '@@IDENTITY',IDENT_CURRENT('TestTB1') AS 'IDENT_CURRENT()'会话2:
INSERT INTO TestTB1 (Data) SELECT 'B'SELECT '会话2',@@IDENTITY AS '@@IDENTITY',IDENT_CURRENT('TestTB1') AS 'IDENT_CURRENT()'那再在会话1里面插入一条数据。这个时候,会话2里面的@@IDENTITY 依然是2,证明@@IDENTITY 是与会话有关的会话1
INSERT INTO TestTB1 (Data) SELECT 'C'SELECT '会话1',@@IDENTITY AS '@@IDENTITY',IDENT_CURRENT('TestTB1') AS 'IDENT_CURRENT()'
会话2
SELECT * FROM dbo.TestTB1SELECT '会话2',@@IDENTITY AS '@@IDENTITY',,IDENT_CURRENT('TestTB1') AS 'IDENT_CURRENT()'模拟一下不同作用域的情况,创建了一个临时存储过程#TEST_PRO,就能看到 同一会话不同作用域的SCOPE_IDENTITY() 并不能获取到种子值
TRUNCATE TABLE dbo.TestTB1goCREATE PROCEDURE #TEST_PROASBEGIN INSERT INTO TestTB1 (Data) SELECT 'A'SELECT @@identity AS '@@identity' , SCOPE_IDENTITY() AS 'SCOPE_IDENTITY()' , IDENT_CURRENT('TestTB1') AS 'IDENT_CURRENT()'ENDgoEXEC #TEST_PROSELECT @@identity AS '@@identity' , SCOPE_IDENTITY() AS 'SCOPE_IDENTITY()' , IDENT_CURRENT('TestTB1') AS 'IDENT_CURRENT()'
那嵌套的情况会怎样呢?再嵌套一层看看,实验结果是跟上面是一致的,在嵌套情况下,作用域不同,SCOPE_IDENTITY() 会重新计数,如下
TRUNCATE TABLE dbo.TestTB1goCREATE PROCEDURE #TEST_PRO_InnerASBEGIN INSERT INTO TestTB1 (Data) SELECT 'A' SELECT 'TEST_PRO_Inner', @@identity AS '@@identity' , SCOPE_IDENTITY() AS 'SCOPE_IDENTITY()' , IDENT_CURRENT('TestTB1') AS 'IDENT_CURRENT()'ENDgoCREATE PROCEDURE #TEST_PROASBEGIN EXEC #TEST_PRO_Inner SELECT 'TEST_PRO', @@identity AS '@@identity' , SCOPE_IDENTITY() AS 'SCOPE_IDENTITY()' , IDENT_CURRENT('TestTB1') AS 'IDENT_CURRENT()' INSERT INTO TestTB1 (Data) SELECT 'B' SELECT 'TEST_PRO_1', @@identity AS '@@identity' , SCOPE_IDENTITY() AS 'SCOPE_IDENTITY()' , IDENT_CURRENT('TestTB1') AS 'IDENT_CURRENT()'ENDgoEXEC #TEST_PROSELECT '外部', @@identity AS '@@identity' , SCOPE_IDENTITY() AS 'SCOPE_IDENTITY()' , IDENT_CURRENT('TestTB1') AS 'IDENT_CURRENT()'
PS:第一次写blog,写得不好,请各位看官多包涵。多指导
新闻热点
疑难解答