Question: What are the different ways of retrieving the identity of last inserted record? Which method do you prefer?
Answer: There are many different ways to do that. Here are three different ways to retrieve the identity of the last inserted record. I personally use SCOPE_IDENTITY () to return the identity of the recently inserted record as it avoids the potential problems associated with adding a trigger.
SELECT @@IDENTITY
It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.
@@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.
SELECT SCOPE_IDENTITY()
It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.
SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.
SELECT IDENT_CURRENT(‘tablename’)
It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.
Reference: Pinal Dave (https://blog.sqlauthority.com)
1 Comment. Leave new
It is possible to use OUTPUT to find the last identity value in cases where the insertion is made in the same session.
Store to a table variable if the value is required for further processing.
create table Test ( TestID int not null identity(1,1 ),
Name varchar(20) not null )
Example #1:
insert into Test ( Name )
output inserted.TestID as IdentityValue
values ( ‘PinalDave’ )
IdentityValue
————-
3
(1 row(s) affected)
Example #2:
declare @IdentityValue table ( IdentityValue int )
insert into Test ( Name )
output inserted.TestID as IdentityValue
into @IdentityValue ( IdentityValue )
values ( ‘PinalDave’ )
select IdentityValue
from @IdentityValue
IdentityValue
————-
5
(1 row(s) affected)