MySQL5.6,使用SIGNAL可以根据变量的值,抛出Exception。
测试数据
create table t1(f1 int);
insert into t1(f1) values(2);
insert into t1(f1) values(12);
insert into t1(f1) values(4);
insert into t1(f1) values(6);
insert into t1(f1) values(7);
存储过程定义
-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE PROCEDURE `my_test`
(
in_c_t int
)
BEGIN
DECLARE my_n_t int;
DECLARE specialty CONDITION FOR SQLSTATE '45000';
SELECT count(1) into my_n_t
FROM t1
WHERE f1 = in_c_t;
IF my_n_t = 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Can not delete!';
end IF;
delete from t1 WHERE f1 = in_c_t;
COMMIT ;
END
执行
call my_test(2);
输出: