如何在儲存過程中編寫一個 MySQL 處理程式來丟擲一個錯誤訊息並繼續執行?


眾所周知,每當 MySQL 儲存過程中發生異常時,都很重要透過丟擲適當的錯誤訊息來處理異常,因為如果我們不處理異常,則極有可能在儲存過程中導致應用程式由於此類異常而失敗。MySQL 提供了一個丟擲錯誤訊息並繼續執行的處理程式。為了展示這一點,我們使用以下示例,其中我們嘗試在主鍵列中插入重複值。

示例

mysql> DELIMITER //
mysql> Create Procedure Insert_Studentdetails(S_Studentid INT, S_StudentName Varchar(20), S_Address Varchar(20))
   -> BEGIN
   -> DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SELECT 'Got an error';
   -> INSERT INTO Student_detail
   -> (Studentid, StudentName, Address)
   -> Values(S_Studentid,S_StudentName,S_Address);
   -> Select * from Student_detail;
   -> END //
Query OK, 0 rows affected (0.19 sec)

呼叫上述過程,如果我們嘗試在列“studentid”中輸入重複值,它將丟擲錯誤訊息“出現錯誤”並繼續執行。

mysql> Delimiter ;
mysql> CALL Insert_Studentdetails(100, 'Gaurav', 'Delhi');
+-----------+-------------+---------+
| Studentid | StudentName | address |
+-----------+-------------+---------+
| 100       | Gaurav      | Delhi   |
+-----------+-------------+---------+
1 row in set (0.11 sec)

Query OK, 0 rows affected (0.12 sec)

mysql> CALL Insert_Studentdetails(101, 'Raman', 'Shimla');
+-----------+-------------+---------+
| Studentid | StudentName | address |
+-----------+-------------+---------+
|       100 | Gaurav      | Delhi   |
|       101 | Raman       | Shimla  |
+-----------+-------------+---------+
2 rows in set (0.06 sec)

Query OK, 0 rows affected (0.12 sec)

mysql> CALL Insert_Studentdetails(101, 'Rahul', 'Jaipur');
+--------------+
| Got an error |
+--------------+
| Got an error |
+--------------+
1 row in set (0.03 sec)

+-----------+-------------+---------+
| Studentid | StudentName | address |
+-----------+-------------+---------+
|       100 | Gaurav      | Delhi   |
|       101 | Raman       | Shimla  |
+-----------+-------------+---------+
2 rows in set (0.04 sec)

Query OK, 0 rows affected (0.05 sec)

mysql> CALL Insert_Studentdetails(103, 'Rahul', 'Jaipur');
+-----------+-------------+---------+
| Studentid | StudentName | address |
+-----------+-------------+---------+
|      100  | Gaurav      | Delhi   |
|      101  | Raman       | Shimla  |
|      103  | Rahul       | Jaipur  |
+-----------+-------------+---------+
3 rows in set (0.08 sec)
Query OK, 0 rows affected (0.10 sec)

更新於: 2020 年 2 月 12 日

631 次檢視

開啟您的 職業

完成課程獲取認證

開始吧
廣告
© . All rights reserved.