Har*_*sha 5 transactions rollback sql-server-2012
我正在使用SQL Server 2012,我用回滚事务编写了一个小的存储过程.我的程序如下:
ALTER PROCEDURE [dbo].[uspInsertEmployee]
@EmpId int,
@EmployeeName varchar(50),
@DeptId int
AS
BEGIN
BEGIN TRY
insert into Departments values (@DeptId, 'Testing 1');
insert into Employees values (@EmpId, @EmployeeName, @DeptId);
END TRY
BEGIN CATCH
--log error here
Goto Error_Rollback
END CATCH
Error_Rollback:
IF @@TRANCOUNT > 0
BEGIN
print 'rolling back transaction' /* <- this is never printed */
ROLLBACK TRAN
END
END
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,在If条件中,当@@ TRANCOUNT> 0时,我正在尝试回滚事务,但是当我执行该过程时,从不执行回滚语句,我已经调试了过程和@的值. @TRANCOUNT是1.但我仍然不明白为什么它不起作用.我知道我们不需要使用begin tran和end tran进行回滚.
任何人都可以帮助我解决这个问题.
编辑
对不起,我忘了提到,第二个插入语句中发生错误.
您已经启动了隐式事务.要回滚,你需要开始一个显式的交易(BEGIN TRANSACTION)
ALTER PROCEDURE [dbo].[uspInsertEmployee]
@EmpId int,
@EmployeeName varchar(50),
@DeptId int
AS
BEGIN
BEGIN TRY
BEGIN TRAN
insert into Departments values (@DeptId, 'Testing 1');
insert into Employees values (@EmpId, @EmployeeName, @DeptId);
COMMIT TRAN
END TRY
BEGIN CATCH
--log error here
Goto Error_Rollback
END CATCH
Error_Rollback:
IF @@TRANCOUNT > 0
BEGIN
print 'rolling back transaction' /* <- this is never printed */
ROLLBACK TRAN
END
END
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18344 次 |
| 最近记录: |