开始使用免费开始使用

失效的事务

您想把两位新客户的数据插入到 customer 表中。您编写了一个脚本,确保一旦发生错误,就回滚事务,并返回错误消息。您希望结合使用 XACT_ABORTXACT_STATE 来进行控制。

本练习是课程的一部分

SQL Server 中的事务与错误处理

查看课程

练习说明

  • 使用合适的 XACT_ABORT 设置。
  • 检查是否存在打开的事务。
  • 回滚该事务。
  • 选取(输出)错误消息。

交互式实操练习

通过完成这段示例代码来试试这个练习。

-- Use the appropriate setting
SET XACT_ABORT ___;
BEGIN TRY
	BEGIN TRAN;
		INSERT INTO customers VALUES ('Mark', 'Davis', '[email protected]', '555909090');
		INSERT INTO customers VALUES ('Dylan', 'Smith', '[email protected]', '555888999');
	COMMIT TRAN;
END TRY
BEGIN CATCH
	-- Check if there is an open transaction
	IF ___() <> 0
    	-- Rollback the transaction
		___;
    -- Select the message of the error
    SELECT ___() AS Error_message;
END CATCH
编辑并运行代码