如何在儲存過程中編寫 MySQL 處理程式,該程式設定變數的特定值並繼續執行?
眾所周知,每當 MySQL 儲存過程中發生異常時,透過丟擲正確的錯誤訊息來處理它非常重要,因為如果不處理異常,則儲存過程中的某個異常可能會導致應用程式失敗。MySQL 提供了一個處理程式,它可以設定變數的特定值並繼續執行。為了演示這一點,我們使用以下示例,其中我們嘗試在主鍵列中插入重複值。
mysql> DELIMITER // mysql> Create Procedure Insert_Studentdetails2(S_Studentid INT, S_StudentName Varchar(20), S_Address Varchar(20),OUT got_error INT) -> BEGIN -> DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET got_error=1; -> 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.00 sec) mysql> Delimiter ; mysql> CALL Insert_Studentdetails2(104,'Ram',‘Chandigarh',@got_error); +-----------+-------------+------------+ | Studentid | StudentName | address | +-----------+-------------+------------+ | 100 | Gaurav | Delhi | | 101 | Raman | Shimla | | 103 | Rahul | Jaipur | | 104 | Ram | Chandigarh | +-----------+-------------+------------+ 4 rows in set (0.04 sec) Query OK, 0 rows affected (0.06 sec)
現在,如果我們嘗試新增列“studentid”的任何重複值,它將繼續執行,給出在過程“select * from student_detail”中編寫的查詢的結果集,並將 got_error 變數的值設定為 1。
mysql> CALL Insert_Studentdetails2(104,'Shyam','Hisar',@got_error); +-----------+-------------+------------+ | Studentid | StudentName | address | +-----------+-------------+------------+ | 100 | Gaurav | Delhi | | 101 | Raman | Shimla | | 103 | Rahul | Jaipur | | 104 | Ram | Chandigarh | +-----------+-------------+------------+ 4 rows in set (0.00 sec) Query OK, 0 rows affected (0.03 sec) mysql> Select @got_error; +------------+ | @got_error | +------------+ | 1 | +------------+ 1 row in set (0.00 sec)
廣告