巢狀 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';
___ ___
___ ___