MySQL自定义函数
自定义函数
- 自定义函数和存储过程很像, 只不过自定义函数不需要手动通过
call
调用 - 而是和其它的聚合函数一样会在SQL语句中自动被调用
- 例如: select avg(score) from stu;
- 例如: select count(*) from stu where age >=18;
创建自定义函数
create function 函数名(形参列表) returns 数据类型 函数特征
begin
sql语句;
... ...
return 值;
end;
函数特征
- DETERMINISTIC: 不确定的
- NO SQL 没有SQl语句,当然也不会修改数据
- READS SQL DATA 只是读取数据,不会修改数据
- MODIFIES SQL DATA 要修改数据
- CONTAINS SQL 包含了SQL语句
调用函数
select 函数名称(参数) from dual;
create function fn_add(a int, b int) returns int DETERMINISTIC
begin
declare sum int default 0;
set sum = a + b;
return sum;
end;
create function check_stu(stuId int) returns varchar(255) DETERMINISTIC
begin
declare stuName varchar(255) default '';
select name into stuName from stu where id=stuId;
return stuName;
end;
查看函数
查看所有函数
show function status;
查看指定数据库中的函数
show function status where db='db_name';
查看函数源代码
show create function show_stu;
删除函数
drop function show_stu;
IF语句
if 条件表达式 then
... ...
elseif 条件表达式 then
... ...
else
... ...
end if;
create function fn_test(age int) returns varchar(255) DETERMINISTIC
begin
declare result varchar(255) default '';
if age >= 18 then
set result = '成年人';
else
set result = '未成年人';
end if;
return result;
end;
create function fn_test2(score int) returns varchar(255) DETERMINISTIC
begin
declare result varchar(255) default '';
if score < 0 || score > 100 then
set result = '没有这个分数';
elseif score < 60 then
set result = '不及格';
elseif score < 80 then
set result = '良好';
else
set result = '优秀';
end if;
return result;
end;
CASE语句
case
when 条件表达式 then
... ...
when 条件表达式 then
... ...
end case;
create function fn_test3(score int) returns varchar(255) DETERMINISTIC
begin
declare result varchar(255) default '';
case
when score=100 then
set result = '还需努力';
when score=0 then
set result = '不需要努力了';
end case;
return result;
end;
循环语句
while 条件表达式 do
... ...
end while;
1 + n 的和 1 + 2 + 3 + 4 + 5
create function fun_test4(num int)returns int DETERMINISTIC
begin
declare sum int default 0;
declare currentIndex int default 1;
while currentIndex <= num do
set sum = sum + currentIndex;
set currentIndex = currentIndex + 1;
end while;
return sum;
end;
repeat
... ...
until 条件表达式 end repeat;
create function fun_test6(num int)returns int DETERMINISTIC
begin
declare sum int default 0;
declare currentIndex int default 1;
repeat
set sum = sum + currentIndex;
set currentIndex = currentIndex + 1;
until currentIndex > num end repeat;
return sum;
end;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具