Don Rhummy
Don Rhummy

Reputation: 25870

Why does my stored procedure throw error 'No data - zero rows fetched, selected, or processed' when I have a "WHERE" in the statement?

I have double checked this select statement and it definitely returns rows:

SELECT name, id FROM MyTable WHERE id > 3;

But when I do it for a cursor, it says no data fetched!

DROP PROCEDURE IF EXISTS Test;
DELIMITER //

CREATE PROCEDURE Test()
BEGIN

    -- Our columns
    DECLARE name VARCHAR(45);
    DECLARE id INT DEFAULT -1;

    -- Our cursor
    DECLARE cur CURSOR FOR SELECT name, id FROM MyTable WHERE id > 3;

    DROP TEMPORARY TABLE IF EXISTS TempTest;
    CREATE TEMPORARY TABLE TempTest
    (
    name VARCHAR(45) NOT NULL,
    id INT NOT NULL
    );

    -- Open our cursor
    open cur;

    -- Start our for loop
    forLoop: LOOP

    -- Get the row
    FETCH cur INTO name, id;

    INSERT INTO TempTest (name, id)
    VALUES ( name, id);

    END LOOP forLoop;

    -- Close the cursor
    CLOSE cur;

    -- NOW GET THE RESULTS
    SELECT * FROM TempTest;

END; //

DELIMITER ;

CALL Test();

It throws the error:

[1329] No data - zero rows fetched, selected, or processed

Upvotes: 2

Views: 3149

Answers (1)

Danilo Bustos
Danilo Bustos

Reputation: 1093

you must define a continue handler:

DROP PROCEDURE IF EXISTS Test;
DELIMITER //

CREATE PROCEDURE Test()
BEGIN

    -- Our columns
    DECLARE name VARCHAR(45);
    DECLARE id INT DEFAULT -1;
    DECLARE done INT DEFAULT 0;
    -- Our cursor
    DECLARE cur CURSOR FOR SELECT name, id FROM MyTable WHERE id > 3;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
    DROP TEMPORARY TABLE IF EXISTS TempTest;
    CREATE TEMPORARY TABLE TempTest
    (
    name VARCHAR(45) NOT NULL,
    id INT NOT NULL
    );

    -- Open our cursor
    open cur;

    -- Start our for loop
    forLoop: LOOP

    -- Get the row
    FETCH cur INTO name, id;
     IF done = 1 THEN
        LEAVE forLoop;
    END IF;
    INSERT INTO TempTest (name, id)
    VALUES ( name, id);

    END LOOP forLoop;

    -- Close the cursor
    CLOSE cur;

    -- NOW GET THE RESULTS
    SELECT * FROM TempTest;

END; //

DELIMITER ;

Upvotes: 5

Related Questions