mysql自定义函数原理与用法实例分析
作者:随风行云 时间:2024-01-28 01:48:20
本文实例讲述了mysql自定义函数原理与用法。分享给大家供大家参考,具体如下:
本文内容:
什么是函数
函数的创建
函数的调用
函数的查看
函数的修改
函数的删除
首发日期:2018-04-18
什么是函数:
函数存储着一系列sql语句,调用函数就是一次性执行这些语句。所以函数可以降低语句重复。【但注意的是函数注重返回值,不注重执行过程,所以一些语句无法执行。所以函数并不是单纯的sql语句集合。】
mysql函数有自己的自定义函数(已经定义好了的函数),想了解更多的可以参考我的另一篇博文:mysql常用函数
这里主要介绍如何自定义函数。
补充:
函数与存储过程的区别:函数只会返回一个值,不允许返回一个结果集。函数强调返回值,所以函数不允许返回多个值的情况,即使是查询语句。
-- 不行的代码:Not allowed to return a result set from a functioncreate function myf()returns int beginselect * from student;return 100;end;
函数的创建:
语法:
create function 函数名([参数列表]) returns 数据类型begin sql语句; return 值;end;
参数列表的格式是: 变量名 数据类型
示例:
-- 最简单的仅有一条sql的函数create function myselect2() returns int return 666;select myselect2(); -- 调用函数--create function myselect3() returns intbegin declare c int; select id from class where cname="python" into c; return c;end;select myselect3();-- 带传参的函数create function myselect5(name varchar(15)) returns intbegin declare c int; select id from class where cname=name into c; return c;end;select myselect5("python");
补充:
还可以有一些特别的选项,特别的选项写在return 之后,begin之前,如:
comment:一个关于函数的描述
还有一些比如sql security等选项,有兴趣可以自行百度。这里不讲解,仅一提有此知识点。
函数的调用:
直接使用函数名()就可以调用【虽然这么说,但返回的是一个结果,sql中不使用select的话任何结果都无法显示出来(所以单纯调用会报错),】
如果想要传入参数可以使用函数名(参数)
调用方式【下面调用的函数都是上面中创建的。】:
-- 无参调用select myselect3();-- 传参调用select myselect5("python");select * from class where id=myselect5("python");
函数的查看:
查看函数创建语句:show create function 函数名;
查看所有函数:show function status [like 'pattern'];
函数的修改:
函数的修改只能修改一些如comment的选项,不能修改内部的sql语句和参数列表。
alter function 函数名 选项;
函数的删除:
drop function 函数名;
希望本文所述对大家MySQL数据库计有所帮助。
来源:https://www.cnblogs.com/progor/p/8871480.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
分享Pandas库中的一些宝藏函数transform()
![](https://img.aspxhome.com/file/2023/7/88017_0s.png)
pandas中DataFrame重置索引的几种方法
vue.js实现简易折叠面板
![](https://img.aspxhome.com/file/2023/1/130271_0s.jpg)
Python采集C站热榜数据实战示例
TensorFlow神经网络创建多层感知机MNIST数据集
python实现的接收邮件功能示例【基于网易POP3服务器】
![](https://img.aspxhome.com/file/2023/1/105611_0s.png)
asp.net生成Excel并导出下载五种实现方法
![](https://img.aspxhome.com/file/2023/9/77189_0s.jpg)
Python3 Tensorlfow:增加或者减小矩阵维度的实现
![](https://img.aspxhome.com/file/2023/8/87828_0s.jpg)
教你使用python搭建一个QQ机器人实现叫起床服务
![](https://img.aspxhome.com/file/2023/7/126957_0s.jpg)
Redux saga异步管理与生成器详解
![](https://img.aspxhome.com/file/2023/9/55999_0s.png)
如何获取当前 select 元素的值
Python字典深浅拷贝与循环方式方法详解
![](https://img.aspxhome.com/file/2023/7/71317_0s.png)
vue-router命名视图的使用讲解
![](https://img.aspxhome.com/file/2023/1/139721_0s.png)
django 将自带的数据库sqlite3改成mysql实例
![](https://img.aspxhome.com/file/2023/3/98813_0s.jpg)
基于python中staticmethod和classmethod的区别(详解)
ASP编程入门进阶(十四):Browser & Linkin
MS IIS server Frontpage Ext Server漏洞
使用PyV8在Python爬虫中执行js代码
python第三方库visdom的使用入门教程
![](https://img.aspxhome.com/file/2023/9/82719_0s.png)