mysql自定义函数(3)条件控制语句

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等等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值