存储过程随记

  1. 存储过程加法计算
DROP PROCEDURE if EXISTS test_add;
CREATE PROCEDURE test_add(IN a int,IN b int,OUT c int)
BEGIN
   IF a IS NULL THEN SET a = 0;
   end IF;
   if b is null THEN set b = 0;
   end IF;
   set c=a+b;
END

执行运算

set @a=1;
CALL test_add(3,@a,@s);
SELECT @s as num;

结果
存储过程随记_第1张图片

  1. 存储过程if判断
drop PROCEDURE if EXISTS test_if;
create PROCEDURE test_if(IN type int)
BEGIN
    DECLARE c VARCHAR(500);
    if type = 1 then set c='param is 1';
    ELSEIF type = 2 then set c='param is 2';
  ELSE set c='param is 3';
    end IF;
    select c;
END

执行存储过程

set @type=1;
call test_if(@type);

结果
存储过程随记_第2张图片

  1. 存储过程case
DROP PROCEDURE if EXISTS test_case;
CREATE PROCEDURE test_case(IN type int)
BEGIN
    DECLARE c VARCHAR(500);
 CASE type 
    WHEN 0 THEN SET c='param0';
  WHEN 1 THEN SET c='param1';
    ELSE set c='param2';
 END CASE;
 SELECT c;
END

执行存储过程

CALL test_case(0);

查看结果
存储过程随记_第3张图片

  1. 存储过程while循环
DROP PROCEDURE IF EXISTS test_while;
CREATE PROCEDURE test_while(IN type int)
BEGIN
    DECLARE a int;
    DECLARE b int;
    set a = 0;
    set b = 0;
    WHILE a<=type DO
        SET b=b+a;
        set a=a+1;
    END WHILE;
    SELECT b;
END;

执行结果
存储过程随记_第4张图片

你可能感兴趣的:(其它)