IDENTITY、SCOPE_IDENTITY、IDENT_CURRENT的分析

https://www.cnblogs.com/daihuiquan/archive/2013/03/18/2956845.html

IDENT_CURRENT、IDENTITY、SCOPE_IDENTITY区别

概念解释

  • IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.html

  • IDENTITY returns the last identity value generated for any table in the current session, across all scopes.session

  • SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope.ide

查找到有中文解释,但仍是发现用英文解释,更容易理解。函数

IDENT_CURRENT,为指定表的全部会话和全部做用域生成的最后一个标识值;
IDENTITY,为当前会话的全部表和全部做用域的最后一个标识值;
SCOPE_IDENTITY,当前会话和当前做用域的全部表的最后一个标识值;

SQL说明

 

复制代码
CREATE TABLE Test1(id int IDENTITY);
CREATE TABLE Test2(id int IDENTITY(100,1));
GO
CREATE TRIGGER Test1ins ON Test1 FOR INSERT 
AS
BEGIN
   INSERT Test2 DEFAULT VALUES
END;
GO
--End of trigger definition

SELECT id FROM Test1;
--IDs empty.
SELECT id FROM Test2;
--ID is empty.

--Do the following in Session 1
INSERT Test1 DEFAULT VALUES;
SELECT @@IDENTITY;
/*Returns the value 100. This was inserted by the trigger.*/

SELECT SCOPE_IDENTITY();
/* Returns the value 1. This was inserted by the 
INSERT statement two statements before this query.*/

SELECT IDENT_CURRENT('Test2');
/* Returns value inserted into Test2, that is in the trigger.*/

SELECT IDENT_CURRENT('Test1');
/* Returns value inserted into Test1. This was the INSERT statement four statements before this query.*/
复制代码

 

全部在执行insert 表A、B、C的事务时候,取IDENT_CURRENT("A")的时候,又没有及时将此ident插入相应记录D,而这个记录表D又要求插入的ident有惟一索引。这时就可能出现惟一索引重复插入失败,由于,在执行事务的时候其它会话,可能已经将此ident插入记录表D。因此这时候用SCOPE_IDENTITY更稳健一点。post

补充

 

session和scope 在博客园找到的概念是这样的:ui

一个做用域 就是一个模块——存储过程、触发器、函数或批处理。所以,若是两个语句处于同一个存储过程、函数或批处理中,则它们位于相同的做用域中。this

会话 一个用户链接产生的全部上下文信息。一个查询分析器窗口就是一个会话spa

可是一个用户connection表明一个session,这个好像不对。code

A connection represents the external connection to the server (over a network or locally through shared memory for example).
A session represents a user process within SQL Server.
A connection may be associated with zero, one, or many sessions.server

Take a look at the columns on sys.dm_exec_connections and sys.dm_exec_sessions. That should give you a feel for the differences.

 sys.dm_exec_connections http://msdn.microsoft.com/zh-cn/library/ms181509.aspx 

sys.dm_exec_sessions  http://msdn.microsoft.com/zh-cn/library/ms176013.aspx

相关文章
相关标签/搜索