11 August, 2010

Different ways to get Identity of New Inserted Rows in SQL Server

There are different methods to know the Identity Value of a newly added row.
Let us consider the following example:

--Create a Table
CREATE TABLE table1
(
id int identity(1,1),
Employee varchar(100)
)

--Insert Data
INSERT INTO table1(Employee) SELECT 'Amit'

--Get Identity Value of the Current Scope
SELECT scope_identity()


--Get Identity value of the Current Session
SELECT @@identity

--Get Identity value of the Table
--Regardless of Scope and Session
SELECT ident_current('table1')
Note that first two methods wont give correct values if data are added to the ‘different tables’.

OUTPUT

No comments:

Post a Comment

Suggestions are invited from readers