如何在 MySQL 中建立帶 OUT 引數的儲存過程?


為了理解,我們使用名為“student_info”的表,該表具有以下值 -

mysql> Select * from student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Jaipur     | Literature |
| 110  | Rahul   | Chandigarh | History    |
| 125  | Raman   | Shimla     | Computers  |
+------+---------+------------+------------+
4 rows in set (0.00 sec)

現在,藉助以下查詢,我們將建立一個帶 OUT 引數的儲存過程,該儲存過程將透過提供科目名稱作為引數來計算特定科目的總數。

mysql> DELIMITER // ;
mysql> Create Procedure subjects (IN S_Subject VARCHAR(25), OUT total INT)
   -> BEGIN
   -> SELECT count(subject)
   -> INTO total
   -> FROM student_info
   -> WHERE subject = S_subject;
   -> END //
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;

'S-Subject' 是 IN 引數,是我們想要統計的科目數,'total' 是 OUT 引數,用於儲存特定科目的科目數。

mysql> CALL subjects('Computers', @total);
Query OK, 1 row affected (0.02 sec)

mysql> Select @total;
+--------+
| @total |
+--------+
|      1 |
+--------+
1 row in set (0.01 sec)

mysql> CALL subjects('History', @total);
Query OK, 1 row affected (0.00 sec)

mysql> Select @total;
+--------+
| @total |
+--------+
|      2 |
+--------+
1 row in set (0.00 sec)

更新時間:2020 年 6 月 22 日

4K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.