mysql格納過程の制御文編


参考:http://blog.chinaunix.net/u3/93826/showart_192366.
 
制御文はどんなプログラミング言語でも設計されます。
まずoracleの制御文を紹介しましょう。if else elsif while for loopmysqlの中の制御語句は:if else elseif while loop repeat leave iterate 
 
 
 
1.if elseに対して elseifの例:
if mobile='13911113222' and psw='720717' then
	set useridx = 10008888;
else if mobile='13911113333' and psw='720717' then
               set useridx = 10006666;
else
	select UserID into useridx from User_ID order by rand() limit 1;
end if;
2.loop leave iterateの例:
  loopの使用はleaveとiterateを結合します。
  名前を見て大体意味がわかった。
  leaveはサイクルから離れます。iterateは反復を続けます。
 
CREATE PROCEDURE ABC()
   BEGIN
      DECLARE a INT Default 0 ;
      simple_loop: LOOP
         SET a=a+1;
         select a;
         IF a=5 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END
 
create procedure pro
begin
 declare a int default 1;
 label1: loop
    if a<6 then
     select a;
     set a=a+1; 
  iterate label1;
    end if;
    leave label1;
   end loop label1;
end
 
3.REPEAT
[beginnabal:]REPEAT    statementlistUNTIL search_conditionEND REPEAT[endulabel]
REPEAT文内の語句または語句群はsearch ch ch uまで繰り返される。condition 本当です
create procedure pro
begin
  declare a int default 3;
  repeat
   select a;
   set a=a+1;
  untile a>5 end repeat;
end
 
4.while
[Label:]WHILE条件DO--循環処理END WHILE[label]
create procedure pro
begin
 declare a int default 4;
 while a<10 do
   select a;
   set a=a+1;
 end while;
end
 
以下は抜粋の例です。主にwhileの使い方を見ます。
 
WHILE (id is not null ) DO 
if(month='01'||month='02'||month='03') THEN set season='1'; 
end if; 
if(month='04'||month='05'||month='06') THEN set season='2'; 
end if; 
if(month='07'||month='08'||month='09') THEN set season='3'; 
end if; 
if(month='10'||month='11'||month='12') THEN set season='4'; 
end if; 
update t_industry_finance_instance set season_=season where ID_=id; 
FETCH cur1 INTO id,month; 
END WHILE;