Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

syntax error on DECLARE CURSOR FOR

I dont't understand why im getting syntax error on my sp code below. Can anyone help me figure this out?

SQL Error (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 pc.prospectus_courses_id FROM prereq_cou' at line 8

DELIMITER $$
DROP PROCEDURE IF EXISTS get_prereqs3$$
CREATE PROCEDURE get_prereqs3(IN prosp_courses_id SMALLINT(5))
BEGIN
    DECLARE done  int DEFAULT FALSE;
    DECLARE required SMALLINT(5) default 0; 
    DECLARE to_search SMALLINT(5) default 0; 
    DROP TABLE IF EXISTS tmp_list;
    CREATE TABLE tmp_list(courses_id SMALLINT(5), courses_id_req SMALLINT(5)) ENGINE = MEMORY;
    DECLARE CUR1 CURSOR FOR SELECT pc.prospectus_courses_id 
            FROM prereq_courses     pc          
            JOIN prerequisites      pr on (pr.id = pc.prerequisites_id)
            JOIN prospectus_courses ps on (ps.id = pr.prospectus_courses_id)
            WHERE ps.id = to_search 
    MAIN_LOOP: LOOP 
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
        OPEN cur1;
        FETCH cur1 INTO required;

        IF done THEN
            CLOSE cur1;
            LEAVE main_loop;
        ELSE
            insert into tmp_list values (to_search, required);
            set to_search = required;
            iterate main_loop;
        END IF;
    END LOOP;
    select  c.course_code 
        from tmp_list           t
        join prospectus_courses pc on pc.id = t.courses_id_req
        join courses            c  on c.id  = pc.courses_id ;
    drop table tmp_list;
END$$
DELIMITER ;
like image 644
tatskie Avatar asked Jan 20 '13 09:01

tatskie


1 Answers

Declarations have to be right after a BEGIN block. In your case just move the DECLARE cur1 CURSOR and DECLARE CONTINUE HANDLER.. two lines up.

Sometimes you want to declare a variable or cursor later in the code, for example only, if a condition is met.

In this case you can wrap the block with a nested BEGIN .. END again.

http://dev.mysql.com/doc/refman/5.5/en/begin-end.html and http://dev.mysql.com/doc/refman/5.5/en/declare.html

DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.

Also you are declaring CUR1 but using cur1.

like image 171
Michel Feldheim Avatar answered Sep 18 '22 13:09

Michel Feldheim