MySQL 在函数内调用存储过程

标签 mysql stored-procedures stored-functions

所以我一直在到处寻找,试图了解如何在存储过程中调用函数,我在这里找到了这个示例:http://forums.mysql.com/read.php?98,175470,175476#msg-175476 .

这帮助我构建了调用存储过程的函数,但是我不断收到此错误:

16:17:51    select regionUtilization(1,2) LIMIT 0, 1000 Error Code: 1415. Not allowed to return a result set from a function    0.000 sec

我想要做的是调用以下存储过程并访问 OUT 变量。然后将其与输入的比较整数进行比较。

drop procedure if exists select_employeesByRegion_proc;
delimiter //
create procedure select_employeesByRegion_proc
(in search int, out result int)
    begin
        select t1.emp_id from (
        select employees.emp_id from branch
        inner join department
        on department.br_id = branch.br_id
        inner join employees
        on employees.dep_id = department.dep_id
        where branch.reg_id = search) as t1;
     set result:=FOUND_ROWS();
     end //
delimiter ;

以下是我目前拥有的功能。

drop function if exists regionUtilization;
delimiter //
create function regionUtilization(search int, compare int)
    returns boolean
begin
    DECLARE temp int;
    call select_employeesByRegion_proc(search, temp);
    if temp >= compare then 
        return true;
    else
        return false;
    end if;
end //
delimiter ;

我还考虑过通过一个计数和另一个返回结果将存储过程的两个方面分离为单独的过程,但这仍然首先要求过程选择一些数据,这会导致与以下相同的错误我已经收到了。

关于如何解决结果集错误有什么建议吗?我不返回结果集,我只是使用该结果集来选择在我的函数中返回 true 还是 false。提前致谢!

最佳答案

谢谢@Barmar 的回答。是的,我需要在程序中使用游标来适本地声明我的函数。

drop procedure if exists build_regionUtil_proc;
delimiter //
create procedure build_regionUtil_proc(in search int, inout result int)
    begin
        declare v_finished integer default 0;
        declare v_list int default 0;
        declare region_cursor cursor for
            select t1.emp_id from (
            select employees.emp_id from branch
            inner join department
            on department.br_id = branch.br_id
            inner join employees
            on employees.dep_id = department.dep_id
            where branch.reg_id = search) as t1;
        declare continue handler
            for not found set v_finished = 1;
        open region_cursor;
        get_results: loop
            fetch region_cursor into v_list;
            if v_finished = 1 then leave get_results;
            end if;
            set result = result + 1;
        end loop get_results;
        close region_cursor;
    end //
delimiter ;

关于MySQL 在函数内调用存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36558793/

相关文章:

sql-server-2008 - 如何在 SQL Server 2008 中将临时数据从触发器传递到存储过程

mysql - 如何将查询结果存入mysql的变量中

java - 如何计算mysql中给定日期内某个项目出现的次数

mysql - 将oracle for循环转换为mysql循环

mysql - 如何为gorm组织多个外键

MySQL:基于 if 语句进行 null 检查

MySQL 创建可以声明和设置选择结果的存储函数

java - 调用返回游标的存储函数

具有多个连接和子查询的 MySQL 搜索查询运行缓慢

Mysql统计用户的列数,并按修改日期分组