hello temp11
hello temp11

Reputation: 141

Getting the Identity value and Inserting into Other table

I am having an Identity element for Table 1 (ID Column).

I make a SP where I insert into Table1 and then I want that identity value to be inserted into other table.

Insert into Table 1 values (Name, RollNo) -- Get the Id of the identity element and insert into other table
Insert into Table 2 values (ID, Standard)

I tried making a temp table

DECLARE @OutputTbl TABLE (ID INT)

Insert into Table 1 values (Name, RollNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)

//But now how should I insert into Table2.

Or is there any other good way ?

Upvotes: 0

Views: 1138

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82534

Use SCOPE_IDENTITY() to get the identity last generated in your stored procedure.

From MSDN:

Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

You can use the following tsql:

DECLARE @ScopeIdentity int

INSERT INTO Table1 VALUES (Name, RollNo)
SELECT @ScopeIdentity = SCOPE_IDENTITY()
INSERT INTO Table2 VALUES (@ScopeIdentity, Standard)

For more information you can read this article by Pinal Dave

update

To enable Rollback as per your question in the comments, you can use a transaction and Try...catch:

DECLARE @ScopeIdentity int
BEGIN TRY
BEGIN TRANSACTION

INSERT INTO Table1 VALUES (Name, RollNo)
SELECT @ScopeIdentity = SCOPE_IDENTITY()
INSERT INTO Table2 VALUES (@ScopeIdentity, Standard)

COMMIT TRANSACTION
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
END CATCH

Upvotes: 1

Related Questions