Identity is the property in table. Identity column values
automatically assigned value whenever new record inserted into a table.
Note: A table having only one identity column.
In real time scenario whenever new record inserted into record we
need to return that Last Identity
value to end user, because of end user application need to check the record
gets inserted successfully or not.
If we want to return the last identity value we have 3 built in
statements in SQL SERVER.
1.
scope_identity ()
2.
@@identity
3.
ident_current
Scope_identity ():
This function returns the last identity genarated value in the current
session and same currnet scope.
@@identity
This function returns the last identity geanrated
value in the current and regardless of scope.
ident_current
In this function we need to pass table name as
input parameter. It will return the last identity genarated value in passed
table regarless of session.
Example:
--Create
Student
if object_id('Student') is null
create table Student(id
int identity(1,1) ,Name varchar(20),Marks int)
In Above Student table is the Id-Identity column.
Open New Query Window :
insert into Student(Name,Marks) values('Rakesh',500)
select scope_identity() as [scope_Identity]
Open New Query Window :
Run this Query
select scope_identity()
as [scope_Identity]
--It will return NULL, Because of Scope_identity () returns the Current
Session only. Here Current Session means whenever new window will open new
session will create. @@Identity also genarated values based on session and scope.
But there is a small diffrence between scope_identity(),@@Identity
Example:
Please truncate all data from Student
truncate table Student
-- Create
Stored Procdure Sub
create procedure Ins_Stu_Sub
(@Name varchar(100),@Marks int)
as
begin
insert into Student(Name,Marks) values(@Name,@Marks)
end
-- Create
Stored Procdure Main
create procedure Ins_Stu_Main
(@Name varchar(100),@Marks int)
as
begin
insert into Student(Name,Marks) values(@Name,@Marks)
exec
Ins_Stu_Sub @Name,@Marks
select scope_identity() as [scope_identity],@@identity as
[identity]
end
--Execute
Main Proceure with Values
exec Ins_Stu_Main 'Rakesh',500
Here Scope_identity returns the same session and same scope
generated value. Here Scope-1 Means Procedure -1, Scope -2 Means Procedure -2
@@identity returns different scope values also .
ident_current:
select ident_current('Student') as[ident_current]
Here ident_current
is accepts table name as input parameter . It does not dependent on session
and scope.
Thanks for sharing Rakesh, ident_current is new for me....
ReplyDelete