轉自:http://www.nuoweb.com/database/7614.html
MySQL有循環語句操作,while 循環、loop循環和repeat循環,目前我只測試了 while 循環,下面與大家分享下
mysql 操作同樣有循環語句操作,網上說有3中標準的循環方式: while 循環 、 loop 循環和repeat循環。還有一種非標準的循環: goto。 鑒于goto 語句的跳躍性會造成使用的的思維混亂,所以不建議使用。
這幾個循環語句的格式如下:
WHILE……DO……END WHILE
REPEAT……UNTIL END REPEAT
LOOP……END LOOP
GOTO。
目前我只測試了 while 循環:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | delimiter $$ // 定義結束符為 $$ drop procedure if exists wk; // 刪除 已有的 存儲過程 create procedure wk() // 創建新的存儲過程 begin declare i int ; // 變量聲明 set i = 1; while i < 11 do // 循環體 insert into user_profile (uid) values (i); set i = i +1; end while; end $$ // 結束定義語句 // 調用 delimiter ; // 先把結束符 回復為; call wk(); |
delimter : mysql 默認的 delimiter是; 告訴mysql解釋器,該段命令是否已經結束了,mysql是否可以執行了。
這里使用 delimiter 重定義結束符的作用是: 不讓存儲過程中的語句在定義的時候輸出。
創建 MySQL 存儲過程的簡單語法為:
1 2 3 4 5 6 7 | CREATE PROCEDURE 存儲過程名稱( [ in | out | inout] 參數 ) BEGIN Mysql 語句 END |
調用存儲過程:
1 | call 存儲過程名稱() // 名稱后面要加() |
1 | < span style = "color: rgb(57, 57, 57); font-family: verdana, 'ms song', Arial, Helvetica, sans-serif; font-size: 14px; line-height: 21px; background-color: rgb(250, 247, 239);" >二 、 REPEAT 循環</ span > |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <pre name = "code" class= "html" >delimiter // drop procedure if exists looppc; create procedure looppc() begin declare i int ; set i = 1; repeat insert into user_profile_company (uid) values (i+1); set i = i + 1; until i >= 20 end repeat; end // ---- 調用 call looppc() |
三、 LOOP 循環
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | delimiter $$ drop procedure if exists lopp; create procedure lopp() begin declare i int ; set i = 1; lp1 : LOOP // lp1 為循環體名稱 LOOP 為關鍵字 insert into user_profile (uid) values (i); set i = i+1; if i > 30 then leave lp1; // 離開循環體 end if; end LOOP; // 結束循環 end $$ |