如何创建从 MySQL 表中返回多个值的 MySQL 存储过程?


我们可以创建一个带有输入输出参数的存储过程以从 MySQL 表中获取多个值。为了让大家理解,我们以名为“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   | Bangalore  | Computers  |
+------+---------+------------+------------+
4 rows in set (0.01 sec)

现在,通过创建名为“select_studentinfo”的过程,如下所示,我们可以通过提供“id”的值从“student_info”表中选择值 -

mysql> DELIMITER // ;
mysql> Create Procedure Select_studentinfo ( IN p_id INT, OUT p_name varchar(20),OUT p_address varchar(20), OUT p_subject varchar(20))
    -> BEGIN
    -> SELECT name, address, subject INTO p_name, p_address, p_subject
    -> FROM student_info
    -> WHERE id = p_id;
    -> END //
Query OK, 0 rows affected (0.03 sec)

在上面的查询中,除了 1 个输入参数之外,它还采用了 4 个输出参数。现在,使用我们希望作为条件提供的如下值来调用该过程 -

mysql> DELIMITER ; //
mysql> CALL Select_studentinfo(110, @p_name, @p_address, @p_subject);
Query OK, 1 row affected (0.06 sec)

mysql> Select @p_name AS Name,@p_Address AS Address, @p_subject AS Subject;
+--------+------------+-----------+
| Name   | Address    | Subject   |
+--------+------------+-----------+
| Rahul  | Chandigarh | History   |
+--------+------------+-----------+
1 row in set (0.00 sec)

更新于: 2020-6-22

2K+ 浏览量

开启您的职业生涯

通过完成该课程获得认证

开始
广告