DECLARE CURSOR FOR上的语法错误

时间:2013-01-20 09:43:05

标签: mysql stored-procedures

我不明白为什么我的sp代码下面会出现语法错误。任何人都可以帮我解决这个问题吗?

SQL错误(1064):

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   'DECLARE CUR1 CURSOR附近选择pc.prospectus_courses_id FROM   在第8行的prereq_cou'

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 ;

2 个答案:

答案 0 :(得分:21)

声明必须在BEGIN块后正确。 在您的情况下,只需移动DECLARE cur1 CURSORDECLARE CONTINUE HANDLER..两行。

有时您希望稍后在代码中声明变量或光标,例如,如果满足条件,则

在这种情况下,您可以再次使用嵌套的BEGIN .. END包装块。

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

  

DECLARE仅允许在BEGIN ... END复合语句中使用,并且必须在其开始之前,在任何其他语句之前。

您还要声明CUR1,但使用cur1

答案 1 :(得分:1)

是否不需要分号?

WHERE ps.id = to_search;
                       ^___________