Search code examples
mysqlsqldatabasestored-proceduresmysql-workbench

Cursor only returning null values


I have the following code (it is not finished yet I am only testing if the cursor is working for now). whenever I select the contents from the cursor, I only get null-values even though there are values in the table.

delimiter //
create procedure get_hr_bp()
begin
    declare done int default false;
    declare hr, sbp, dbp, new_hr, new_sbp, new_dbp numeric(3,0);
    declare cur cursor for select hr, sbp, dbp from patient;
    DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = true;
    
    open cur;
    read_loop: loop
        fetch cur into hr, sbp, dbp;
        select hr, sbp, dbp;
        
        
        if done then
            leave read_loop;
        end if;
        
    end loop;
    close cur;
    
end//
delimiter ;



Solution

  • You are using same variables names hr, sbp, dbp which are also your column names.

    create procedure get_hr_bp()
    begin
        declare done int default 0;
        declare new_hr, new_sbp, new_dbp numeric(3,0);
        declare cur cursor for select hr, sbp, dbp from patient;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
        
        open cur;
        read_loop: loop
            fetch cur into new_hr, new_sbp, new_dbp;
            select new_hr, new_sbp, new_dbp;
            
            if done then
                leave read_loop;
            end if;
    
        end loop;
        close cur;
    end;