目录

介绍

案例

介绍

存储函数是有返回值的存储过程,存储函数的参数只能是IN类型的。具体语法如下:

CREATE FUNCTION 存储函数名称 ([ 参数列表 ])

RETURNS type [characteristic ...]

BEGIN

-- SQL语句

RETURN ...;

END ;

characteristic说明:

DETERMINISTIC:相同的输入参数总是产生相同的结果NO SQL :不包含 SQL 语句。READS SQL DATA:包含读取数据的语句,但不包含写入数据的语句。

案例

计算从1累加到n的值,n为传入的参数值。

create function fun(n int)

returns int deterministic

begin

declare total int default 0;

while n>0 do

set total := total + n;

set n := n - 1;

end while;

return total;

end;

当我们要执行上述定义存储函数的语句时,会出现报错,这是因为:

在mysql8.0版本中binlog默认是开启的,一旦开启了,mysql就要求在定义存储函数时,需要指定 characteristic特性,否则就会报如下错误

所以应该改为:

create function fun(n int)

returns int deterministic

begin

declare total int default 0;

while n>0 do

set total := total + n;

set n := n - 1;

end while;

return total;

end;

select fun(50);

 需要说明的是:

存储函数使用的情况很少,因为存储函数能实现的,存储过程同样也能实现;而且,存储函数必须要有返回值。

END

学习自:黑马程序员——MySQL数据库课程

参考阅读

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。