MySQL 如何编写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)
阅读更多:MySQL 教程