MySQL if语句序列存储函数

时间:2011-04-26 09:23:06

标签: mysql if-statement sequence stored-functions

我在MYSQL中使用IF语句有一个奇怪的问题。 我有一个存储函数,它将表的内容作为字符串返回。为了让我的字符串返回正确的结果数,我根据一个数字准备一个select语句。如果数字是< = 9则是一个sql语句而另一个是高于另一个。

但是,在序列中我只能将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; 

END

1 个答案:

答案 0 :(得分:0)

您的代码段中存在的问题是语句的顺序。 您在声明语句之前发出SET语句。声明应按如下方式订购:

  1. 变量和条件声明。
  2. 游标声明。
  3. 处理程序声明。
  4. 程序代码。
  5. 尝试按照上述说明命令您运行,它应该可以工作。 另外不要忘记将END $$添加到您的函数中。