This is actually a combination of all three answers. You call a nonexistent procedure to raise the error, and then you declare an exit handler that catches the error you received. Here is an example using SQLSTATE 42000 (the procedure does not exist) to throw an error before deleting if the row to be deleted has a foreign key identifier:
DROP PROCEDURE IF EXISTS decount_test; DELIMITER // CREATE DEFINER = 'root'@'localhost' PROCEDURE decount_test ( p_id bigint ) DETERMINISTIC MODIFIES SQL DATA BEGIN DECLARE EXIT HANDLER FOR SQLSTATE '42000' SELECT 'Invoiced barcodes may not have accounting removed.'; IF (SELECT invoice_id FROM accounted_barcodes WHERE id = p_id ) THEN CALL raise_error; END IF; DELETE FROM accounted_barcodes WHERE id = p_id; END // DELIMITER ;
Output:
call decount_test(123456); +----------------------------------------------------+ | Invoiced barcodes may not have accounting removed. | +----------------------------------------------------+ | Invoiced barcodes may not have accounting removed. | +----------------------------------------------------+
Ryan M Apr 22 '10 at 18:31 2010-04-22 18:31
source share