如何创建一个从 MySQL 表返回多个值的 MySQL 存储过程?
我们可以创建一个具有 IN和OUT参数的存储过程,以获取 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 个 IN 参数外,它还使用了 4 个 OUT 参数。现在,使用我们要作为条件提供的以下值调用该过程,如下所示 -
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)
广告