0%

数据库系统概念原书 第6版 图5-5 创建函数的SQL代码报错

数据库系统概念原书 第6版 图5-5 创建函数的SQL代码报错

问题描述

数据库系统概念原书 第6版 图5-5 SQL中定义的函数中定义存储过程的SQL代码如下.

1
2
3
4
5
6
7
8
9
create function dept_count(dept_name varchar(20))
returns integer
begin
declare d_count integer;
select count(*) into d_count
from instructor
where instructor.dept_name = dept_name
return d_count;
end;

但是我在MySQL 8.0中运行上述命令,报错如下:

1
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'return d_count; end' at line 8

解决方案

这是因为select语句没有以分号结束,修改为如下即可:

1
2
3
4
5
6
7
8
9
create function dept_count(dept_name varchar(20))
returns integer
begin
declare d_count integer;
select count(*) into d_count
from instructor
where instructor.dept_name = dept_name;
return d_count;
end;

新问题

不过还是有错误:

1
1418 - This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)

解决方案

执行下面的语句,然后再执行创建存储过程的语句即可.

1
SET GLOBAL log_bin_trust_function_creators = 1;
1
2
3
4
5
6
7
8
9
10
11
12
13
mysql> SET GLOBAL log_bin_trust_function_creators = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> create function dept_count(dept_name varchar(20))
returns integer
begin
declare d_count integer;
select count(*) into d_count
from instructor
where instructor.dept_name = dept_name;
return d_count;
end;
Query OK, 0 rows affected (0.02 sec)

原文链接: 数据库系统概念原书 第6版 图5-5 创建函数的SQL代码报错