微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

mysql--存储过程 + 函数

I. 存储过程

  1. 创建存储过程

  2. 参数声明

  3. 变量声明

  4. 设置变量

  5. while 循环语句

  6. 条件语句(if | case)

  7. call 调用存储过程

示例代码

delimiter //

create procedure cal(in sNum int,in eNum int,out total int) comment '计算函数' begin
declare tmpVal int default 0;

set tmpVal = 0;

while sNum <= eNum do 
    tmpVal = tmpVal + sNum;
    sNum   = sNum + 1;
end while;

-- 方式1: case when condition then value else value end;
-- set rel = case when tmpVal < 50 then set total = 0 
--      when tmpVal > 50 then set total = tmpVal 
-- else 
--    set tmpVal = 50
-- end;

-- 方式2:if condition then statement elseif condition statement else statement end if
if total < 50 then 
    set rel = 0;
elseif total > 50 then 
    set rel = total;
else 
    set rel = 50;
end if;

end//

delimiter ;

call cal(1,10,@total) // @total = 55
select @total; // 55

II. 函数

delimiter //

create function sayName(name char(50)) returns varchar(255) deterministic
begin
return concat('欢迎 ',name,'!');
end//

delimiter ;

select sayName('cxl');

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐