MySQL流程控制实例

1、IF ELSE

DROP PROCEDURE IF EXISTS if_else_example;
CREATE PROCEDURE if_else_example(

IN p_type TINYINT 

)
COMMENT 'if_else_example'

BEGIN

DECLARE m_varINTDEFAULT0;

IF p_type =1THEN
SET m_var =1;

ELSEIF p_type =2THEN
SET m_var =2;

ELSE
SET m_var =3;

ENDIF;

SELECT m_var;

END;



 

2、CASE WHEN

DROP PROCEDUREIFEXISTS case_when_example;
CREATE PROCEDURE case_when_example(

IN p_type TINYINT 

)
COMMENT 'case_when_example'

BEGIN

DECLARE m_varINTDEFAULT0;

CASE p_type

WHEN 1THEN
  SET m_var= m_var+1;
  SET m_var= m_var+1;

WHEN 2THEN
  SET m_var= m_var+2;
  SET m_var= m_var+2;

WHEN 3THEN
  SET m_var= m_var+3;
  SET m_var= m_var+3;

ENDCASE;

SELECT m_var;

END;




 

3、WHILE DO

DECLARE iINTDEFAULT0;
WHILE i <100 DO
SET i = i +1;
ENDWHILE;


 

4、使用LEAVE语句强制退出存储过程

DROPPROCEDUREIFEXISTS leave_example;
CREATEPROCEDURE leave_example(
OUT p_out INT
)
begin_label:BEGIN

DECLARE m INTDEFAULT5;

IF m >1THEN
SET p_out =1;
LEAVE begin_label;
ENDIF;

IF m >2THEN
SET p_out =2;
LEAVE begin_label;
ENDIF;

IF m >3THEN
SET p_out =3;
LEAVE begin_label;
ENDIF;

END;

/* CALL leave_example(@s); 结果:1*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值