2

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; 

終わり

4

1 に答える 1

0

コード セグメントでの問題は、ステートメントの順序です。宣言ステートメントの前に SET ステートメントを発行します。ステートメントは次のように並べる必要があります。

  1. 変数と条件の宣言。
  2. カーソル宣言。
  3. ハンドラー宣言。
  4. プログラムコード。

上記のように機能するように注文してみてください。機能するはずです。また、関数に END$$ を追加することを忘れないでください。

于 2011-04-28T20:44:13.797 に答える