【发布时间】:2015-02-16 01:42:38
【问题描述】:
我正在寻找一种方法来围绕一些 SQL 脚本语句创建一个“包装器”,这些语句既可以是事务性的(提交/回滚),又可以在屏幕上为运行脚本的用户提供某种错误消息。
从另一个问题,我发布了我发现看起来不错的解决方案...
我可以在 TRY 内进行交易,如果发生任何错误,它应该转到 CATCH 并允许我向用户发送消息。
今天我有一个 INSERT 失败,它没有跳转到 CATCH,它只是给了我一个错误(INSERT 语句中的列数比 VALUES 子句中指定的值多。 VALUES 子句必须与 INSERT 语句中指定的列数匹配。)
谁能帮我理解发生了什么以及为什么它没有触发 CATCH?
这里是完整的代码...
USE master;
-- Hide Record Counts
SET NOCOUNT ON;
-- Wrap Everything in a TRY -If we get any error it will jump to CATCH and stop executing the script
BEGIN TRY;
-- Start TRANSACTION within the TRY
BEGIN TRANSACTION;
print('');
print('========= Step XX ==> START');
Print('');
Print('(( Some Action XXXX ))');
print('');
Create table #TempTest (
field1 varchar(10) null,
field2 varchar(10) null,
field3 varchar(10) null);
-- I will try to insert only 2 of the 3 columns so that I can trigger an error
-- Why does this not kick over to the CATCH?
INSERT INTO #TempTest (field1, field2, field3)
VALUES ('value1','value2');
-- COMMIT Transaction - If we had encountered an error it would have jumped to the CATCH block
COMMIT;
print('');
print('========= Step XX ==> FINISHED');
Print('');
-- End the TRY wrapper
END TRY
-- Here is the CATCH if we have any errors in the TRY section this will execute
BEGIN CATCH
-- We need to make sure something actually happened that can be ROLLBACK
IF @@TRANCOUNT > 0
BEGIN
ROLLBACK;
print('');
print('>>>>>>>>>>>>>>>>>>>>>>> Opps we ran into some kind of ERROR. <<<<<<<<<<<<<<<<<<<<<<');
print('');
END;
END CATCH;
-- Reset the NOCOUNT to Off
SET NOCOUNT OFF;
【问题讨论】:
标签: sql transactions try-catch