在 MySQL 儲存過程中設定條件


若要在儲存過程中設定條件,在 MySQL 中使用 IF...ELSE。以下是 if-else 的語法 −

IF yourCondition then
      yourStatement1,
 ELSE    
      yourStatement2,
 END IF;

讓我們在一個儲存過程中實現以上語法 −

mysql> DELIMITER //
mysql> CREATE PROCEDURE IF_ELSE_DEMO(IN value int)
   -> BEGIN
   ->    SET @val=value;
   ->    IF @val > 10 then
   ->       select concat(@val,' is greater than 10');
   ->    ELSE
   ->        select concat(@val,' is less than 10 ');
   ->    END IF;
   -> END;
   -> //
Query OK, 0 rows affected (0.16 sec)
mysql> DELIMITER ;

現在你可以使用 CALL 命令呼叫儲存過程 −

mysql> call IF_ELSE_DEMO(18);

這將產生以下輸出 −

+------------------------------------+
| concat(@val,' is greater than 10') |
+------------------------------------+
| 18 is greater than 10              |
+------------------------------------+
1 row in set (0.03 sec)
Query OK, 0 rows affected (0.04 sec)

更新於: 2019 年 12 月 10 日

654 次瀏覽

開啟你的 職業

完成課程以獲取認證

開始
廣告
© . All rights reserved.