2011-04-26 65 views
2

我在使用MYSQL中的IF语句时遇到了特殊的问题。 我有一个存储的函数,以字符串的形式返回表的内容。为了让我的字符串返回正确数量的结果,我准备了一个基于数字的select语句。如果数字是< = 9,那么一个sql语句和另一个以上的9。MySQL如果存储函数中的语句序列

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

+0

找到了答案。游标可能不会在选择类型后使用! – 2011-04-26 10:43:05

回答

0

你在你的代码段的问题是,你的语句的顺序。 您在声明语句之前发出SET语句。声明应按如下顺序排列:

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

试着订购你的功能,如上所述,它应该工作。 也不要忘了添加END $$到你的函数。