MySQL在函数内调用存储过程

时间:2016-04-11 20:37:57

标签: 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。提前谢谢!

1 个答案:

答案 0 :(得分:0)

谢谢@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 ;