Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for using @@identity rather than scope_identity

On a SQL Server 2005 database, one of our remote developers just checked in a change to a stored procedure that changed a "select scope_identity" to "select @@identity". Do you know of any reasons why you'd use @@identity over scope_identity?

like image 867
Lance Fisher Avatar asked Dec 09 '08 17:12

Lance Fisher


People also ask

What is the difference between @@ Identity and Scope_identity?

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.

What is the use of @@ identity and Scope_identity?

The @@identity function returns the last identity created in the same session. The scope_identity() function returns the last identity created in the same session and the same scope. The ident_current(name) returns the last identity created for a specific table or view in any session.

What is @@ identity used for?

After an INSERT, SELECT INTO, or bulk copy statement is completed, @@IDENTITY contains the last identity value that is generated by the statement. If the statement did not affect any tables with identity columns, @@IDENTITY returns NULL.

Is Scope_identity thread safe?

Answers. Both are thread safe function. It only hold current scope or last execution's value.


3 Answers

@@IDENTITY will return the last identity value issued by the current session. SCOPE_IDENTITY() returns the last identity value in the current session and same scope. They are usually the same, but assume a trigger is called which inserted something somewhere just before the current statement. @@IDENTITY will return the identity value by the INSERT statement of the trigger, not the insert statement of the block. It's usually a mistake unless he knows what he's doing.

like image 111
mmx Avatar answered Oct 05 '22 23:10

mmx


Here is a link that may help differentiate them

looks like:

  • IDENTITY - last identity on the connection
  • SCOPE_IDENTITY - last identity you explicitly created (excludes triggers)
  • IDENT_CURRENT(’tablename’) - Last Identity in table regardless of scope or connection.
like image 35
Jamal Hansen Avatar answered Oct 06 '22 01:10

Jamal Hansen


I can't think of any, unless there was a trigger then inserted a row (or somesuch) and I really really wanted the id of that trigger-inserted row rather than the row I physically changed.

In other words, no, not really.

  • DISCLAIMER: Not a T-SQL expert :)
like image 23
Andrew Rollings Avatar answered Oct 05 '22 23:10

Andrew Rollings