Anup Shah on WPF and Silverlight (Programming Garden)

IT 's For You!!!

Thursday, August 24, 2017

Get the last generated Identity column value in SQL Server

In SQL Server Identity column values are auto created. 

There are multiple ways in sql server, to retrieve the last identity value that is generated. The most common way is to use SCOPE_IDENTITY() built in function.  

Apart, from using SCOPE_IDENTITY(), you also have @@IDENTITY and IDENT_CURRENT('TableName') function. But there are certain very important variation that needs to be taken care. which is explained as below,


Example,

Select SCOPE_IDENTITY()
Select @@IDENTITY
Select IDENT_CURRENT('GalaxyEmployees')

Let's now understand the difference between three of the different scenarios,

SCOPE_IDENTITY() returns the last identity value that is created in the same session (Connection) and in the same scope (in the same session and same scope - Stored procedure, function, trigger). 

Let's say, I have 2 tables GalaxyEmployee1 and GalaxyEmployee2, and I have a trigger on GalaxyEmployee1 table, which will insert a record into GalaxyEmployee2 table. 

So, when we insert a record into GalaxyEmployee1 table, SCOPE_IDENTITY() returns the identity value that is generated in GalaxyEmployee1 table, where as @@IDENTITY returns, the value that is generated in GalaxyEmployee2 table. So, @@IDENTITY returns the last identity value that is created in the same session without any consideration to the scope. 

IDENT_CURRENT('GalaxyEmployees') returns the last identity value created for a specific table across any session and any scope.

In brief:
SCOPE_IDENTITY() - Returns the last identity value that is created in the same session and in the same scope.

@@IDENTITY - Returns the last identity value that is created in the same session and across any scope.

IDENT_CURRENT('Table') - Returns the last identity value that is created for a specific table across any session and any scope.
, , , ,

No comments:

Post a Comment