hopeless-dream

导航

MySQL存储过程---流程控制(分支)

case

语法

方法1:等值判断
case 变量|表达式|字段
when 判断的值 then 结果或语句;
when 判断的值 then 结果或语句;
...
else 结果或语句
end case;


方法2:
case
when 条件1 then 语句;
when 条件2 then 语句;
else 语句
end case;

实例

创建存储过程

DELIMITER $$

USE `world`$$

DROP PROCEDURE IF EXISTS `p_case`$$

CREATE DEFINER=`root`@`10.0.0.%` PROCEDURE `p_case`( IN salary INT)
BEGIN
    DECLARE res VARCHAR(10);
    
    CASE 
    WHEN salary < 5000
    THEN SET res = 'too low';
    WHEN salary < 10000
    THEN SET res = 'low';
    WHEN salary < 25000
    THEN SET res = 'middle';
    ELSE
      SET res = 'high';
     END CASE;
    
    SELECT res;
    END$$

DELIMITER ;

调用

 

 

if

语法

if 
条件1 then 语句1;
elseif 条件2 then 语句2;
...;
else 语句n;
end if;

实例 1

DELIMITER $$

USE `world`$$

DROP PROCEDURE IF EXISTS `p_if`$$

CREATE DEFINER=`root`@`10.0.0.%` PROCEDURE `p_if`( IN age INT)
BEGIN
    
    DECLARE ret VARCHAR(20);
    
    IF age < 10
      THEN
    SET ret = 'little';
    ELSEIF age BETWEEN 10 AND 20
      THEN
    SET ret = 'yonung';
    ELSE
    SET ret = 'other';
    END IF;
    SELECT ret;
    END$$

DELIMITER ;

调用

 

 

实例 2

判断用户名、密码是否正确

CREATE TABLE t3 (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(20) NOT NULL,
passwd VARCHAR(20) NOT NULL)
ENGINE=INNODB CHARSET utf8;

INSERT INTO t3 VALUES(1,'tom','tompass'),(2,'jerry','jerrypass');

创建存储过程

DELIMITER $$

CREATE
    /*[DEFINER = { user | CURRENT_USER }]*/
    PROCEDURE `world`.`verify`(IN u VARCHAR(20), IN p VARCHAR(20))
    /*LANGUAGE SQL
    | [NOT] DETERMINISTIC
    | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
    | SQL SECURITY { DEFINER | INVOKER }
    | COMMENT 'string'*/
    BEGIN
    DECLARE num INT DEFAULT 0;
    DECLARE res VARCHAR(20);
    
    SELECT COUNT(*) INTO num FROM t3 WHERE t3.username=u AND t3.passwd=p;
    CASE
    WHEN num >0
    THEN SET res = 'successful';
    ELSE
    SET res='faild';
    END CASE;
    SELECT res;

    END$$

DELIMITER ;

调用

 

posted on 2020-06-15 00:14  hopeless-dream  阅读(507)  评论(0编辑  收藏  举报