我使用下面的SQL来删除记录并在事务中插入Customers表。如果insert语句中有错误,我看到错误消息,当我尝试执行select * from customers
时,它不显示结果集。当我关闭SSMS窗口时,它显示There are uncommitted transactions. Do you wish to commit these transactions before closing the window?
单击“确定”后,将从表格中显示结果。那么,在使用事务时是否存在任何锁定机制。
USE CMSDB;
BEGIN TRY
BEGIN TRAN t1;
DELETE FROM Customers
print @@trancount -->prints 3 since there are three records
INSERT INTO CUSTOMERS
INSERT INTO CUSTOMERd --> error here
INSERT INTO CUSTOMERS
COMMIT TRAN t1;
END TRY
BEGIN CATCH
print 'hi' --> not printing
select @@trancount --> not resulting anything
IF @@TRANCOUNT > 0
ROLLBACK TRAN t1;
-- Error Message
DECLARE @Err nvarchar(1000)
SET @Err = ERROR_MESSAGE()
RAISERROR (@Err,16,1)
END CATCH
GO
消息
(3 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
Msg 208, Level 16, State 1, Line 8
Invalid object name 'dbo.Customerd'.
答案 0 :(得分:2)
摘自TRY…CATCH说明:
当CATCH块不处理以下类型的错误 它们与TRY ... CATCH结构处于相同的执行级别:
编译阻止批量运行的错误,例如语法错误。
语句级重新编译期间发生的错误,例如因编译后出现的对象名称解析错误 延期名称解析。
在这种情况下会发生什么
错误未被捕获,控制权从TRY ... CATCH中消失 构建到更高的水平。