IDENT_CURRENT ,@@identity,SCOPE_IDENTITY() 之间对比
IDENT_CURRENT ,@@identity,SCOPE_IDENTITY() 之间对比
- IDENT_CURRENT 返回为某个会话和用域中的指定表生成的最新标识值。
- @@IDENTITY 返回为跨所有作用域的当前会话中的某个表生成的最新标识值。
- SCOPE_IDENTITY() 返回为当前会话和当前作用域中的某个表生成的最新标识值。
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()\'
1 INSERT INTO TestTB1 (Data) SELECT \'A\' 2 SELECT \'会话1\',@@IDENTITY AS \'@@IDENTITY\',IDENT_CURRENT(\'TestTB1\') AS \'IDENT_CURRENT()\'
INSERT INTO TestTB1 (Data) SELECT \'B\' SELECT \'会话2\',@@IDENTITY AS \'@@IDENTITY\',IDENT_CURRENT(\'TestTB1\') AS \'IDENT_CURRENT()\'
INSERT INTO TestTB1 (Data) SELECT \'C\' SELECT \'会话1\',@@IDENTITY AS \'@@IDENTITY\',IDENT_CURRENT(\'TestTB1\') AS \'IDENT_CURRENT()\'
会话2
SELECT * FROM dbo.TestTB1 SELECT \'会话2\',@@IDENTITY AS \'@@IDENTITY\',,IDENT_CURRENT(\'TestTB1\') AS \'IDENT_CURRENT()\'
TRUNCATE TABLE dbo.TestTB1 go CREATE PROCEDURE #TEST_PRO AS BEGIN INSERT INTO TestTB1 (Data) SELECT \'A\' SELECT @@identity AS \'@@identity\' , SCOPE_IDENTITY() AS \'SCOPE_IDENTITY()\' , IDENT_CURRENT(\'TestTB1\') AS \'IDENT_CURRENT()\' END go EXEC #TEST_PRO SELECT @@identity AS \'@@identity\' , SCOPE_IDENTITY() AS \'SCOPE_IDENTITY()\' , IDENT_CURRENT(\'TestTB1\') AS \'IDENT_CURRENT()\'
那嵌套的情况会怎样呢?再嵌套一层看看,实验结果是跟上面是一致的,在嵌套情况下,作用域不同, SCOPE_IDENTITY() 会重新计数,如下
TRUNCATE TABLE dbo.TestTB1 go CREATE PROCEDURE #TEST_PRO_Inner AS BEGIN INSERT INTO TestTB1 (Data) SELECT \'A\' SELECT \'TEST_PRO_Inner\', @@identity AS \'@@identity\' , SCOPE_IDENTITY() AS \'SCOPE_IDENTITY()\' , IDENT_CURRENT(\'TestTB1\') AS \'IDENT_CURRENT()\' END go CREATE PROCEDURE #TEST_PRO AS BEGIN 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()\' END go EXEC #TEST_PRO SELECT \'外部\', @@identity AS \'@@identity\' , SCOPE_IDENTITY() AS \'SCOPE_IDENTITY()\' , IDENT_CURRENT(\'TestTB1\') AS \'IDENT_CURRENT()\'
PS:第一次写blog,写得不好,请各位看官多包涵。多指导