简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM