January 26, 2012

IDENT_CURRENT in SQL Server

Recently i faced a very good question from someone.
Question was something like:

There are multiple insert statements in my stored procedure i want to get last inserted ID
from specified table not form last inserted table.

If i will use @@IDENTITY it will give ID from last statement table only.

Let’s create a simple example:

CREATE TABLE Ax1
(Ax1ID INT IDENTITY(1,1), Ax1Val VARCHAR(5))

CREATE TABLE Ax2
(Ax2ID INT IDENTITY(2,1), Ax2Val VARCHAR(5))

CREATE TABLE Ax3
(Ax3ID INT IDENTITY(3,1), Ax3Val VARCHAR(5))

CREATE PROCEDURE spGetLastInsertedValue
AS
BEGIN

      INSERT INTO Ax1
      (Ax1Val)
      SELECT 'Ax1'

      INSERT INTO Ax2
      (Ax2Val)
      SELECT 'Ax2'

      INSERT INTO Ax3
      (Ax3Val)
      SELECT 'Ax3'

      SELECT @@IDENTITY
      -- It will give me last inserted ID from Ax3
      SELECT IDENT_CURRENT('Ax2') AS 'Last Inserted ID in Ax2'
     
END

EXEC
spGetLastInsertedValue


Output will be something like as below:

image

No comments:

Post a Comment