SQL Day 8: Retrieving Identity Column Values
LO1: How to get the last generated identity value
LO2: Difference between SCOPE_IDENTITY(), @@IDENTITY and IDENT_CURRENT(‘Table_Name’)
Prerequisite: SQL Day 7: Identity Column in SQL Server
Let’s say we have two table as ‘Test1’ and ‘Test2’ with the column as ‘ID’ and value.
Create table Test1(
ID int identity(1,1),--(1,1) repersent seed and increment respectively
Value nvarchar(50)
)
Create table Test2(
ID int identity(1,1),--(1,1) repersent seed and increment respectively
Value nvarchar(50)
)
Let’s insert the value in Test1 table.
insert into Test1 values ('A')
When we retrieve the value from the Test1 table so you should see the ID column value gets generated automatically because ID column is the Identity column.
As you can see we have inserted a record in Test1 table and ID value get automatically generated as 1.
Now how do we retrieve the last generated value?
To do that we have the built-in SQL function called SCOPE_IDENTITY()
select SCOPE_IDENTITY()
There is an another way to get the identity value, to use the global variable @@IDENTITY
select @@IDENTITY
Difference between SCOPE_IDENTITY() and @@IDENTITY
To understand the difference I have created a Trigger on Test1 table which will insert data into Test2 table whenever we insert data in Test1 table.
Note: Trigger will be covered in the later session. In a short, Trigger can be created on a table for a specific action. For example, whenever any insert is performed on Test1 table, a new row should be inserted in Test2 table.
Syntax:
create trigger TRIGGER_NAME on TABLE_NAME for Insert
as
Begin
--Code to execute
End
Example:
create trigger trForInsert on Test1 for Insert
as
Begin
insert into Test2 values ('ZZZ')
End
Now insert a new record in Test1 table, this will also trigger the created trigger on Test1 table and insert a record in Test2 as well.
Now execute the SCOPE_IDENTITY() and @@IDENTITY at the same time.
SCOPE_IDENTITY() return the result as 2 where as @@IDENTITY return the result as 1.
This is happening because SCOPE_IDENTITY() return the Identity value of Same Session (a Session is nothing but a connection to a SQL Server) and the Same Scope and @@IDENTITY return the Identity value of the Same Session and any Scope.
We have another function to get the identity value called IDENT_CURRENT(‘Table_Name’), this will return the identity of the specific table across any session and any scope.
That’s all for today. Thank You.
Comments
Post a Comment