在 TSQL 事务中,我有一个将记录插入到 a中的操作,以及使用记录列的值MyTable1
更新 a 的操作,这仅在事务提交后插入。那么,如何在实际插入表之前获取这个自动生成的值呢?MyTable2
Identity
MyTable1
代码只是为了说明问题:
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