自定义函数
-- 创建函数
-- create function 函数名(参数),returns 数据类型
-- begin
-- 函数体
-- 返回值
-- end
delimiter $$
create function display1() returns int
begin
return 100;
end
$$
delimiter ;
-- 调用函数 select 函数名(参数列表)
select display1();
+------------+
| display1() |
+------------+
| 100 |
+------------+
-- 查看函数
show function status like ;
show function status\G
*************************** 23. row ***************************
Db: test
Name: display1
Type: FUNCTION
Definer: root@localhost
Modified: 2019-06-09 23:28:04
Created: 2019-06-09 23:28:04
Security_type: DEFINER
Comment:
character_set_client: utf8mb4
collation_connection: utf8mb4_0900_ai_ci
Database Collation: utf8mb4_0900_ai_ci
23 rows in set (0.00 sec)
-- 查看函数的创建语句
show create function display1;
-- 删除函数
drop function display1;
-- *****************************************************************
-- 函数的参数
delimiter $$
create function display1(int_1 int) returns int
begin
set @i=1;
set @res=0;
while @i<int_1 do
set @res = @res+@i;
set @i=@i+1;
end while;
return @res;
end
$$
delimiter ;
select display1(100);
+---------------+
| display1(100) |
+---------------+
| 4950 |
+---------------+
-- 在函数内部通过@定义的变量 在函数外部也可以访问
select @res,@i;
+------+------+
| @res | @i |
+------+------+
| 4950 | 100 |
+------+------+
-- 函数作用域
-- 全局变量可以在任何地方定义 局部变量只能在函数内部调用
-- 全局变量:使用set关键字定义 使用@符号标志
-- 局部变量:使用declare 关键字申明 没有@符号 ,所有的局部变量必须在函数体开始前定义
-- 实例:求1到10的和但是要求5的倍数不加
delimiter $$
create function display2(int_1 int) returns int
begin
declare i int default 1;
declare res int default 0;
mywhile:while i<=int_1 do
if i % 5 =0 then
set i=i+1;
iterate mywhile;
end if;
set res = res+i;
set i=i+1;
end while;
return res;
end
$$
delimiter ;
select display2(10);
+--------------+
| display2(10) |
+--------------+
| 40 |
+--------------+