tatskie
tatskie

Reputation: 445

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 ;

Upvotes: 11

Views: 23913

Answers (2)

Michel Feldheim
Michel Feldheim

Reputation: 18250

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.

Upvotes: 31

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

Is there no need semicolon?

WHERE ps.id = to_search;
                       ^___________

Upvotes: 1

Related Questions