我有一个运行时间很长的脚本,我想包装其中可能包含多达100多个事务的事务。
我想实现一些错误处理和代码重用。我正在考虑使用标签和GOTO语句。
BEGIN TRY
BEGIN TRANSACTION abc
--DO SOMETHING
COMMIT TRANSACTION abc;
END TRY
BEGIN CATCH
GOTO ERROR_OUT
END CATCH
ERROR_OUT:
SELECT ERROR_MESSAGE() [ErrorMessage];
ROLLBACK;
Run Code Online (Sandbox Code Playgroud)
使用许多事务时是否应该这样做?
在我强制执行错误的简单测试中,我注意到ERROR_MESSGE()SELECT语句未返回结果。
有没有办法在使用标签时使select语句返回结果?
Declare @Table table (Num float,Den float,Pct float)
Insert into @Table values (25,100,0),(50,0,0)
BEGIN TRY
BEGIN TRANSACTION abc
-- Force a Divide by Zero on 2nd record
Update @Table Set Pct=Num/Den
COMMIT TRANSACTION abc;
Select * from @Table
GOTO CLEAN_OUT
END TRY
BEGIN CATCH
Declare @Error varchar(max)=Error_Message()
GOTO ERROR_OUT
END CATCH
ERROR_OUT:
ROLLBACK;
Select ErrorMessage=@Error
Select * From @Table
CLEAN_OUT:
Go
Run Code Online (Sandbox Code Playgroud)
退货
ErrorMessage
Divide by zero error encountered.
Num Den Pct
25 100 0
50 0 0
Run Code Online (Sandbox Code Playgroud)
然后尝试使用(50,125,0)