ตามที่ทราบว่าเมื่อเกิดข้อยกเว้นใน MySQL Stored Procedure การจัดการข้อยกเว้นโดยการโยนข้อความผิดพลาดที่เหมาะสมนั้นสำคัญมาก เพราะหากเราไม่จัดการข้อยกเว้น จะมีโอกาสที่แอปพลิเคชันจะล้มเหลวด้วยข้อยกเว้นนั้นใน Stored Procedure MySQL มี Handler ที่ใช้ SQLSTATE สำหรับข้อผิดพลาดเริ่มต้นของ MySQL และออกจากการดำเนินการ เพื่อสาธิต เราใช้ตัวอย่างต่อไปนี้ ซึ่งเราพยายามแทรกค่าซ้ำในคอลัมน์ Primary Key
ตัวอย่าง
mysql> Delimiter //
mysql> Create Procedure Insert_Studentdetails4(S_Studentid INT, S_StudentName Varchar(20), S_Address Varchar(20),OUT got_error INT)
-> BEGIN
-> DECLARE EXIT HANDLER FOR 1062 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)
ตอนนี้ หากเราพยายามเพิ่มค่าซ้ำของคอลัมน์ studentid มันจะออกจากการดำเนินการ ไม่ให้ชุดผลลัพธ์ของคำสั่งใน Procedure select * from student_detail และให้แค่ข้อความผิดพลาดเริ่มต้นของ MySQL 1062 เกี่ยวกับการใส่ค่าซ้ำ และตั้งค่าตัวแปร got_error เป็น 1
mysql> Delimiter ; mysql> CALL Insert_Studentdetails4(104,'Ram','Chandigarh',@got_error); Query OK, 0 rows affected (0.00 sec) mysql> Select @got_error; +------------+ | @got_error | +------------+ | 1 | +------------+ 1 row in set (0.00 sec)