程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> MySQL綜合教程 >> mysql數據庫條件判斷查詢語句的常見寫法說明

mysql數據庫條件判斷查詢語句的常見寫法說明

編輯:MySQL綜合教程

大家都知道只有的了mysql 5後才出現了存儲過程,這些用法,那麼我們要在sql 中用if else while這些,就得用存過程或函數來實例了。

mysql> DELIMITER //
mysql> CREATE FUNCTION myFunction (quantity INT(10)) RETURNS INT(10)
    -> BEGIN
    ->
    ->     WHILE quantity MOD 12 > 0 DO
    ->     SET quantity = quantity + 1;
    ->     END WHILE;
    ->
    ->     RETURN quantity;
    ->
    -> END
    -> //
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;
mysql>
mysql> select myFunction(10);
+----------------+
| myFunction(10) |
+----------------+
|             12 |
+----------------+
1 row in set (0.00 sec)

mysql>
mysql> select myFunction(24);
+----------------+
| myFunction(24) |
+----------------+
|             24 |
+----------------+
1 row in set (0.00 sec)

實例二

mysql> delimiter //
mysql> create procedure test_while (IN in_count INT)
    -> BEGIN
    ->     declare count INT default 0;
    ->
    ->     while count < 10 do
    ->         set count = count + 1;
    ->     end while;
    ->
    ->     select count;
    -> END
    -> //
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql> delimiter ;
mysql>
mysql> call test_while(10);
+-------+
| count |
+-------+
|    10 |
+-------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

帶有條件判斷的

mysql> delimiter $$
mysql>
mysql> CREATE PROCEDURE myProc()
    -> BEGIN
    ->
    ->     DECLARE i int;
    ->     SET i=1;
    ->     loop1: WHILE i<=10 DO
    ->          IF MOD(i,2)<>0 THEN /*Even number - try again*/
    ->             SELECT CONCAT(i," is an odd number");
    ->          END IF;
    ->          SET i=i+1;
    ->     END WHILE loop1;
    -> END$$
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql> delimiter ;
mysql> call myProc();
+-------------------------------+
| CONCAT(i," is an odd number") |
+-------------------------------+
| 1 is an odd number            |
+-------------------------------+
1 row in set (0.02 sec)

+-------------------------------+
| CONCAT(i," is an odd number") |
+-------------------------------+
| 3 is an odd number            |
+-------------------------------+
1 row in set (0.02 sec)

+-------------------------------+
| CONCAT(i," is an odd number") |
+-------------------------------+
| 5 is an odd number            |
+-------------------------------+
1 row in set (0.02 sec)

+-------------------------------+
| CONCAT(i," is an odd number") |
+-------------------------------+
| 7 is an odd number            |
+-------------------------------+
1 row in set (0.02 sec)

+-------------------------------+
| CONCAT(i," is an odd number") |
+-------------------------------+
| 9 is an odd number            |
+-------------------------------+
1 row in set (0.02 sec)

Query OK, 0 rows affected (0.38 sec)

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved