日期:2014-05-16  浏览次数:21119 次

SCOPE_IDENTITY、IDENT_CURRENT 和 @@IDENTITY的区别比较
1.三者的区别:

1)IDENT_CURRENT 返回为任何会话和任何作用域中的特定表最后生成的标识值。

2)@@IDENTITY 返回为当前会话的所有作用域中的任何表最后生成的标识值。

3)SCOPE_IDENTITY 返回为当前会话和当前作用域中的任何表最后生成的标识值。(防止返回触发器中的insert的IDENTITY值)

2.详细的说明:
引用

SCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY are similar functions because they return values that are inserted into identity columns.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT (Transact-SQL).

SCOPE_IDENTITY and @@IDENTITY return the last identity values that are generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; @@IDENTITY is not limited to a specific scope.

For example, there are two tables, T1 and T2, and an INSERT trigger is defined on T1. When a row is inserted to T1, the trigger fires and inserts a row in T2. This scenario illustrates two scopes: the insert on T1, and the insert on T2 by the trigger.

Assuming that both T1 and T2 have identity columns, @@IDENTITY and SCOPE_IDENTITY will return different values at the end of an INSERT statement on T1. @@IDENTITY will return the last identity column value inserted across any scope in the current session. This is the value inserted in T2. SCOPE_IDENTITY() will return the IDENTITY value inserted in T1. This was the last insert that occurred in the same scope. The SCOPE_IDENTITY() function will return the null value if the function is invoked before any INSERT statements into an identity column occur in the scope.


详细参考:http://msdn.microsoft.com/en-us/library/ms190315.aspx