Search code examples
mysqlstored-procedurescursorsql-delete

MySQL - delete in stored procedure with cursor


I am creating a stored procedure containing a delete statement and a cursor usage. The problem is that I cannot use those two together.

Here's a self-contained MWE. Note that Block 1 and Block 2 can be run separately (if I comment the other one), but not together.

drop table if exists T1;
create table T1(f1 int, f2 int);
insert into T1 values(1, 1);
insert into T1 values(2, 2);
insert into T1 values(3, 3);

drop table if exists T2;
create table T2(f3 int, f4 int);
insert into T2 values(1, 11);
insert into T2 values(2, 22);
insert into T2 values(3, 33);


drop procedure if exists proc1;
DELIMITER //
CREATE PROCEDURE proc1(inputValue int)
    BEGIN
    declare i int;
    declare cursorSize int;
    declare anF1 int;
    declare anF2 int;

    -- Block 1 - Begin:    
    delete from T2 where f3 = inputValue;
    -- Block 1 - End.    
    
    -- Block 2 - Begin:    
    declare cur1 cursor for 
        select f1, f2  
            from T1
            where f1 <= inputValue;
    open cur1;

    select FOUND_ROWS() into cursorSize;
    if (cursorSize > 0) then
        set i = 0;
        while i < cursorSize DO
            fetch cur1 into anF1, anF2;
                insert into T2 values(anF1, anF2);
            set i = i + 1;
            end while;
        end if;

    close cur1;
    -- Block 2 - End.    
    
    END //
DELIMITER ;

call proc1(3);

I receive this error if I uncomment the delete statement in Block 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

    'declare cur1 cursor for 
    select f1, f2  
        from T1
        where f1 <=' at line 10

Please help me resolve the issue.


Solution

  • The documentation does not seem to explicitly state it, but I am fairly certain no queries may precede a cursor declaration.

    You should be able to execute that DELETE after the CURSOR is DECLAREd but before it is OPENed.