Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apparently fetch returns NULL

I am learning stored procedures, cursors in mysql and I stumble on it:

delimiter //

CREATE PROCEDURE some_func()
BEGIN
    DECLARE link_rewrite VARCHAR(255);
    DECLARE link_rewrite_cursor CURSOR FOR SELECT link_rewrite FROM prod;

    OPEN link_rewrite_cursor;

    SET @count = 0;

    WHILE @count < 10 DO
        FETCH link_rewrite_cursor INTO link_rewrite;
        SELECT link_rewrite;
        set @count = @count + 1;
    END WHILE;

    CLOSE link_rewrite_cursor;

END//

delimiter ;

My question is: Why SELECT link_rewrite always returns NULL (in prod table there is 9000 rows). SELECT link_rewrite FROM prod returns a lot of rows(9000 rows).

like image 298
PaulP Avatar asked Jan 04 '12 18:01

PaulP


1 Answers

You should avoid using the same name for multiple different things. Specifically, give the variable a different name than the column you are selecting. For example, if you rename the variable v_link_rewrite then it will probably work:

delimiter //

DROP PROCEDURE IF EXISTS some_func //

CREATE PROCEDURE some_func()
BEGIN
    DECLARE v_link_rewrite VARCHAR(255);
    DECLARE link_rewrite_cursor CURSOR FOR SELECT link_rewrite FROM prod;

    OPEN link_rewrite_cursor;

    SET @count = 0;

    WHILE @count < 10 DO
        FETCH link_rewrite_cursor INTO v_link_rewrite;
        SELECT v_link_rewrite;
        set @count = @count + 1;
    END WHILE;

    CLOSE link_rewrite_cursor;

END//

delimiter ;
like image 101
Ike Walker Avatar answered Oct 18 '22 16:10

Ike Walker