1、if语句:
drop function if exists hello; --删除函数
create function hello(a int) returns varchar (255) --创建函数,并且有一个int类型名称为a的变量
begin
declare x varchar(255) default ' x ';
select `name` into x from gl_dept where id = a;
-- if开始
if x = '淘宝网店2' THEN set x = '2';
elseif x = '淘宝网店3' THEN set x = '3';
else set x = '5';
end if; -- if结束
return x;
end;
2、case when语句:
drop function if exists hello;
create function hello(a int) returns varchar (255)
begin
declare x varchar(255) default ' x ';
declare y varchar(255);
select `name` into x from gl_dept where id = a;
-- 开始
case
when x = '淘宝网店1' then set y = '你好';
when x = '淘宝网店2' then set y = '你好1';
else set y = '你好2' ;
end case; -- 结束
return y;
end;
上面的这两个语句,和直接在sql里面写的时候,是有些区别的。sql里面的if和case when结尾和在自定义函数里面是不同的,要注意。
3、loop循环语句(无条件循环,就是不需要条件就可以进入循环):
drop function if exists hello;
create function hello(a int) returns varchar (255)
begin
declare x int;
declare y int;
set y = a;
-- 开始循环
myloop:loop
set y = y - 1;
-- if这里是满足条件后,用来跳出循环用的。
if y = 1 then
leave myloop;
end if;
end loop; -- 结束循环
return y;
end;
上面的”myloop“是声明这个循环的名字,跳出循环的时候用,”leave“,是用来跳出循环的,
4、while do 循环(有条件循环,就是必须要有条件才可以进入循环):
drop function if exists hello;
create function hello(a int) returns varchar (255)
begin
declare x int;
declare y int;
set y = a;
-- 开始循环
while y < 10 do
set y = y + 1;
end while; -- 结束循环
return y;
end;
自定义函数里面可以加入sql语句,可以加入mysql本身的一些函数,如sunm,count等等。