您可以在存储过程和IF()
select语句中使用IF 。
IF() in select statement mysql> select if(0=0,'Hello MySQL','condition is wrong');
这将产生以下输出-
+------------------------------------------------------+ | if('test'='test','Hello MySQL','condition is wrong') | +------------------------------------------------------+ | Hello MySQL | +------------------------------------------------------+ 1 row in set (0.00 sec)
第二种情况,如果您的条件出错-
mysql> select if(1=0,'Hello MySQL','condition is wrong');
这将产生以下输出-
+--------------------------------------------+ | if(1=0,'Hello MySQL','condition is wrong') | +--------------------------------------------+ | condition is wrong | +--------------------------------------------+ 1 row in set (0.00 sec)
创建存储过程的查询如下。在这里,我们使用IF设置条件-
mysql> DELIMITER // mysql> CREATE PROCEDURE if_demo(value int) BEGIN IF 1=value THEN SELECT "Hello MySQL"; ELSE SELECT "Wrong Condition"; END IF; END // mysql> DELIMITER ;
现在,您可以使用call命令来调用存储过程。
mysql> call if_demo(1);
这将产生以下输出-
+-------------+ | Hello MySQL | +-------------+ | Hello MySQL | +-------------+ 1 row in set (0.00 sec)
如果您的条件为假-
mysql> call if_demo(0);
这将产生以下输出-
+-----------------+ | Wrong Condition | +-----------------+ | Wrong Condition | +-----------------+ 1 row in set (0.00 sec)