2

我在 MYSQL 中使用 IF 语句有一个特殊的问题。我有一个存储函数,它将表的内容作为字符串返回。为了让我的字符串返回正确数量的结果,我准备了一个基于数字的选择语句。如果数字是 <= 9,那么一个 sql 语句和 9 个以上的另一个。

但是,在序列中,我只能将 if 语句放在函数的末尾。如果我把它放在正确的位置,它当前被注释掉,它会给我一个语法错误。如果我将 if 语句放在函数的末尾不正确的地方,我不会收到错误。

请帮忙。我不知道这是一个错误还是我自己的错误。

DELIMITER $$

CREATE DEFINER=`root`@`localhost` FUNCTION `returnstring`(IDGrade int) RETURNS varchar(255) CHARSET latin1
BEGIN
Declare fSubjectID, sSubjectID varchar (255);
declare sqlstatement varchar(255);

#Declare variable for done of loop
Declare done int default 0;

#Declare variables from the select statement
#IF     IDGRADE <= 9 then set sqlstatement = 'SELECT subjectID FROM subjecttb where sectType = "b" or secttype = "j" order by subjectID';
#ELSEIF IDGRADE > 9  then set sqlstatement = 'SELECT subjectID FROM subjecttb where sectType = "b" or secttype = "s" order by subjectID';
#END IF; 


#Declare a cursor to iterate through the table
declare cursor1 cursor for 
        SELECT subjectID
        FROM `marksdb`.`subjecttb` 
        where sectType = 'b' or secttype = 'j' order by subjectID;

#Continue loop until nothing is found anymore
declare continue handler for not found set done=1;

#Runs the select statement
open cursor1;

#Declares a loop
set fsubjectid='';
SubjectID_loop:loop
    Fetch cursor1 into sSubjectID;
    if done=1 then # no more rows to fetch
          leave SubjectID_loop;
    end if;
    set fSubjectID = concat(fSubjectID, sSubjectID , ' varchar (255), ');
end loop SubjectID_loop;
set fSubjectID = substring(fSubjectID, 1, length(fsubjectid)-2);
close cursor1;

return fSubjectID;

#Declare variables from the select statement
IF IDGRADE <= 9 then set sqlstatement = 'SELECT subjectID FROM subjecttb where sectType = "b" or secttype = "j" order by subjectID';
ELSEIF IDGRADE > 9  then set sqlstatement = 'SELECT subjectID FROM subjecttb where sectType = "b" or secttype = "s" order by subjectID';
END IF; 

结尾

4

1 回答 1

0

您在代码段中遇到的问题是您的语句的顺序。在声明语句之前发出 SET 语句。语句应按以下顺序排列:

  1. 变量和条件声明。
  2. 光标声明。
  3. 处理程序声明。
  4. 程序代码。

尝试按上述方式订购您的功能,它应该可以工作。也不要忘记将 END$$ 添加到您的函数中。

于 2011-04-28T20:44:13.797 回答