MYSQL で IF ステートメントを使用する際に特有の問題があります。テーブルの内容を文字列として返すストアド関数があります。文字列が正しい数の結果を返すようにするには、数値に基づいて選択ステートメントを準備します。数が <= 9 の場合、1 つの SQL ステートメントと 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;
終わり