8

我不明白为什么我在下面的 sp 代码上出现语法错误。谁能帮我解决这个问题?

SQL 错误 (1064):

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 8 行的“DECLARE CUR1 CURSOR FOR SELECT pc.prospectus_courses_id FROM 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 ;
4

2 回答 2

25

声明必须在BEGIN块之后。在您的情况下,只需将DECLARE cur1 CURSORandDECLARE 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.

于 2013-01-20T09:59:20.093 回答
1

不需要分号吗?

WHERE ps.id = to_search;
                       ^___________
于 2013-01-20T09:52:58.733 回答