SCOPE_IDENTITY() in sql server

 SCOPE_IDENTITY()

Returns the last identity value generated in the same scope and session, excluding values from triggers or nested procedures. This function ensures the most reliable and scoped identity retrieval when working with identity columns in SQL.

Scenarios:

  1. Retrieving the identity value after an insert to use in subsequent operations, ensuring it's from the current insert and not from any triggers or procedures.
  2. Referencing the parent record's identity when inserting related child records.
  3. Dealing with triggers, ensuring the identity value comes from the original insert, not any triggered inserts.
  4. Managing multiple inserts in a stored procedure, capturing and using identity values across different tables.
  5. Ensuring consistency in transactions, where inserts into multiple tables are rolled back if any fail, maintaining consistent identity values.

To handle these scenarios, use SCOPE_IDENTITY() to capture the correct identity and manage transactions for data integrity.

 

Example:

CREATE PROCEDURE InsertOrderWithDetails

    @CustomerID INT,

    @OrderDate DATETIME,

    @OrderDetails TABLE (ProductID INT, Quantity INT, Price DECIMAL(10, 2))

AS

BEGIN

    DECLARE @OrderID INT;

 

    BEGIN TRY

        BEGIN TRANSACTION;

 

        INSERT INTO Orders (OrderDate, CustomerID)

        VALUES (@OrderDate, @CustomerID);

 

        SET @OrderID = SCOPE_IDENTITY();

 

        INSERT INTO OrderDetails (OrderID, ProductID, Quantity, Price)

        SELECT @OrderID, ProductID, Quantity, Price

        FROM @OrderDetails;

 

        COMMIT TRANSACTION;

 

        SELECT @OrderID AS NewOrderID;

 

    END TRY

    BEGIN CATCH

        ROLLBACK TRANSACTION;

 

        THROW;

    END CATCH;

END;

 

Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced