在 MySQL 存储过程中,如何检查局部变量是否为 null?
对此,请使用 COALESCE()。我们实现一个存储过程来检查局部变量是否为 null −
mysql> DELIMITER // mysql> CREATE PROCEDURE local_VariableDemo() BEGIN DECLARE value1 int; DECLARE value2 int; select value1,value2; select concat('After checking local variable is null the sum is = ',COALESCE(value1,0)+COALESCE(value2,0)); END // Query OK, 0 rows affected (0.19 sec) mysql> DELIMITER ;
使用 CALL 命令调用存储过程 −
mysql> call local_VariableDemo();
这将生成以下输出 −
+--------+--------+ | value1 | value2 | +--------+--------+ | NULL | NULL | +--------+--------+ 1 row in set (0.00 sec) +-----------------------------------------------------------------------------------------------------+ | concat('After checking local variable is null the sum is = ',COALESCE(value1,0)+COALESCE(value2,0)) | +-----------------------------------------------------------------------------------------------------+ | After checking local variable is null the sum is = 0 | +-----------------------------------------------------------------------------------------------------+ 1 row in set (0.01 sec) Query OK, 0 rows affected (0.03 sec)
广告