3

我正在使用下面的 SQL 来删除记录并插入到事务中的客户表中。如果插入语句中有错误,我会看到错误消息,并且当我尝试执行时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'.
4

1 回答 1

2

摘自TRY…CATCH描述:

以下类型的错误发生在与 TRY...CATCH 构造相同的执行级别时,不会由 CATCH 块处理:

  • 编译错误,例如语法错误,阻止批处理运行。

  • 在语句级重新编译期间发生的错误,例如 由于延迟名称解析而在编译后发生的对象名称解析错误

在这种情况下会发生什么

错误没有被捕获,并且控制从 TRY…CATCH 构造传递到下一个更高级别。

于 2013-08-23T20:01:17.263 回答