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