嵌套 TRY...CATCH 结构
您想在 buyers 表中登记一位新买家。该买家名为 Peter Thomson,电子邮箱是 [email protected],电话号码是 555000100。
在您的数据库中,还有一张名为 errors 的表,用于存储每个错误。
您需要编写一个脚本,在插入该用户数据时控制可能出现的错误。同时将这些错误插入到 errors 表中。
您会如何准备这个脚本?
本练习是课程的一部分
SQL Server 中的事务与错误处理
练习说明
- 使用一个
TRY块包裹INSERT INTO buyers语句。 - 使用一个
CATCH块包裹错误处理。 - 使用另一个
TRY块包裹INSERT INTO errors语句。 - 使用另一个
CATCH块包裹内层(嵌套)的错误处理。
交互式实操练习
通过完成这段示例代码来试试这个练习。
-- Set up the first TRY block
___ ___
INSERT INTO buyers (first_name, last_name, email, phone)
VALUES ('Peter', 'Thompson', '[email protected]', '555000100');
___ ___
-- Set up the first CATCH block
___ ___
SELECT 'An error occurred inserting the buyer! You are in the first CATCH block';
-- Set up the nested TRY block
___ ___
INSERT INTO errors
VALUES ('Error inserting a buyer');
SELECT 'Error inserted correctly!';
___ ___
-- Set up the nested CATCH block
___ ___
SELECT 'An error occurred inserting the error! You are in the nested CATCH block';
___ ___
___ ___