zoukankan      html  css  js  c++  java
  • mysql之自定义函数


    本文内容:

    • 什么是函数
    • 函数的创建
    • 函数的调用
    • 函数的查看
    • 函数的修改
    • 函数的删除

    首发日期:2018-04-18


    什么是函数:

    • 函数存储着一系列sql语句,调用函数就是一次性执行这些语句。所以函数可以降低语句重复。【但注意的是函数注重返回值,不注重执行过程,所以一些语句无法执行。所以函数并不是单纯的sql语句集合。】
    • mysql函数有自己的自定义函数(已经定义好了的函数),想了解更多的可以参考我的另一篇博文:mysql之常用函数
    • 这里主要介绍如何自定义函数。

    补充:

    • 函数与存储过程的区别:函数只会返回一个值,不允许返回一个结果集。函数强调返回值,所以函数不允许返回多个值的情况,即使是查询语句。
      -- 不行的代码:Not allowed to return a result set from a function
      create function myf()returns int 
      begin
      select * 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 int
      begin 
          declare c int;
          select id from class where cname="python" into c;
          return c;
      end;
      select myselect3();
      -- 带传参的函数
      create function myselect5(name varchar(15)) returns int
      begin 
          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 函数名;

  • 相关阅读:
    putty如何退出全屏模式
    maven项目如何生成war文件
    使用web.xml方式加载Spring时,获取Spring context的两种方式
    Mybatis 示例之 SelectKey
    psql主主复制
    【转】angular使用代理解决跨域
    Error: EACCES: permission denied when trying to install ESLint using npm
    Run Code Once on First Load (Concurrency Safe)
    [转]对于BIO/NIO/AIO,你还只停留在烧开水的水平吗
    golang 时间的比较,time.Time的初始值?
  • 原文地址:https://www.cnblogs.com/progor/p/8871480.html
Copyright © 2011-2022 走看看