Inside a TSQL transaction I have an operation of inserting a record into a MyTable1 and an operation of updating a MyTable2 with a value of Identity column of the MyTable1 record, which is only to be inserted after the transaction is commited.
So, how to get this autogenerated value before it is actually inserted into the table?
Code just to illustrate the question:
CREATE TABLE MyTable1(
MyTable1Id int identity(1,1) primary key,
Field1 varchar(50)
)
CREATE TABLE MyTable2(
MyTable2Id int identity(1,1) primary key,
MyTable1Id int
)
CREATE PROCEDURE MyProc(
@MyVal1 [varchar](50)
)
AS
BEGIN TRAN
-- try to insert
INSERT INTO MyTable1(
Field1
)
SELECT @MyVal1
IF @@ERROR <> 0
BEGIN
ROLLBACK TRAN
END
-- update MyTable2
DECLARE @TheUnknownIdValue int
UPDATE MyTable2
SET MyTable1Id = @TheUnknownIdValue -- how to get the value needed here?
WHERE ...
IF @@ERROR <> 0
BEGIN
ROLLBACK TRAN
END
COMMIT TRAN
Use
SCOPE_IDENTITY()just after theINSERT