Nesting TRY...CATCH constructs
You want to register a new buyer in your buyers table. This new buyer is Peter Thomson. His e-mail is [email protected] and his phone number is 555000100.
In your database, there is also a table called errors, in which each error is stored.
You prepare a script that controls possible errors in the insertion of this person's data. It also inserts those errors into the errors table.
How do you prepare the script?
Este exercício faz parte do curso
Transactions and Error Handling in SQL Server
Instruções do exercício
- Surround the
INSERT INTO buyersstatement with aTRYblock. - Surround the error handling with a
CATCHblock. - Surround the
INSERT INTO errorsstatement with anotherTRYblock. - Surround the nested error handling with another
CATCHblock.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
-- 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';
___ ___
___ ___