我想使用事务将记录插入到分层表中。执行完其showing命令后,成功完成但记录未插入表中。如果缺少某些内容,请参见下面的脚本:
CREATE TABLE dev_emp_master
(
id int identity(1,1) primary key,
name char(2)
)
GO
CREATE TABLE dev_emp_child
(
id int identity(1,1) primary key,
mid int foreign key references dev_emp_master(id),
addr char(3)
)
BEGIN TRANSACTION [T_MIGRATION]
BEGIN TRY
DECLARE @masterId INT;
SET IDENTITY_INSERT [dbo].[dev_emp_master] OFF;
INSERT INTO dev_emp_master (name) VALUES('A');
SET @masterId = scope_identity();
SET IDENTITY_INSERT [dbo].[dev_emp_child] OFF;
INSERT INTO dev_emp_child(mid,addr) VALUES(@masterId,'ABC');
SET IDENTITY_INSERT [dbo].[dev_emp_child] ON;
SET IDENTITY_INSERT [dbo].[dev_emp_master] ON;
COMMIT TRANSACTION [T_MIGRATION]
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION [T_MIGRATION]
END CATCH
GO
答案 0 :(得分:0)
SET IDENTITY_INSERT [dbo].[dev_emp_child] ON;
SET IDENTITY_INSERT [dbo].[dev_emp_master] ON;
那是问题。无法同时为两个表打开Identity_Insert。
如果您放置
,则可以轻松地对代码进行故障排除 Print ERROR_MESSAGE()
在您的捕获块中。