如何在 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)
广告