声明mysql上的游标错误“SQL语法错误”

时间:2015-06-30 18:09:54

标签: mysql database cursor

请在这里帮忙

delimiter $
create procedure corrige_preg()
begin
    declare var_test integer;
    declare var_contador integer;
    set var_contador = 1;
    select test_tnum into var_test from preg
    group by test_tnum having max(pnum)<>count(pnum);
    if var_test is null then
        select "ok";
    else
        declare var_cursor cursor for
        select pnum from preg where test_tnum = var_test;
        open var_cursor;
        loop1: loop
            fetch var_cursor into pnum;
            pnum = var_contador;
            set var_contador=var_contador+1;
        end loop loop1;
        close var_cursor;
    end if;
end $
  

错误:您的SQL语法出错;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   'declare var_cursor游标,用于从preg中选择pnum   第11行的test_tnum = var_test'

2 个答案:

答案 0 :(得分:0)

将光标声明移动到变量声明后面的顶部。

例如:

delimiter $
create procedure corrige_preg()
begin
    declare var_test integer;
    declare var_contador integer;
    declare var_pnum integer;

    declare var_cursor cursor for
    select pnum from preg where test_tnum = var_test;   

    set var_contador = 1;
    select test_tnum into var_test from preg
    group by test_tnum having max(pnum)<>count(pnum);
    if var_test is null then
        select "ok";
    else        
        open var_cursor;
        loop1: loop
            fetch var_cursor into var_pnum;
            -- var_pnum = var_contador;
            set var_contador=var_contador+1;
        end loop loop1;
        close var_cursor;
    end if;
end $

答案 1 :(得分:0)

声明必须在BEGIN之后,因此在BEGIN块周围包裹END / ELSE块。您还需要pnum的声明,并且必须使用SET语句分配给它。

delimiter $
create procedure corrige_preg()
begin
    declare var_test integer;
    declare var_contador integer;
    set var_contador = 1;
    select test_tnum into var_test from preg
    group by test_tnum having max(pnum)<>count(pnum);
    if var_test is null then
        select "ok";
    else begin
        declare pnum integer;
        declare var_cursor cursor for
        select pnum from preg where test_tnum = var_test;
        open var_cursor;
        loop1: loop
            fetch var_cursor into pnum;
            set pnum = var_contador;
            set var_contador=var_contador+1;
        end loop loop1;
        close var_cursor;
    end;
    end if;
end $
delimiter ;