我们可以使用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 //
现在,使用我们想要提供的值调用该过程,如下所示:
mysql> DELIMITER ; // mysql> CALL Select_studentinfo(110, @p_name, @p_address, @p_subject); 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)