编写mysql存储过程时,最好设置SQL_MODE,比如下面的例子:
DELIMITER //
CREATE FUNCTION test(p_first TINYINT, p_second TINYINT) RETURNS TINYINT
BEGIN
DECLARE v_result TINYINT;
SET v_result := p_first + p_second;
RETURN v_result;
END//
DELIMITER ;
看上去是正确的,比如调用:
mysql> select test(126,1);
+-------------+
| test(126,1) |
+-------------+
| 127 |
+-------------+
1 row in set (0.00 sec)
但:
mysql> select test(127,1);
+-------------+
| test(127,1) |
+-------------+
| 127 |
+-------------+
1 row in set, 1 warning (0.00 sec)
就错误了,因为用了tinyint,
所以,强烈建议编译存储过程时,设置sql_mode,比如:
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='STRICT_TRANS_TABLES';
然后当再运行存储过程时,可以有提示:
mysql> select test(127,1);
ERROR 1264 (22003): Out of range value for column 'v_result' at row 1