MySQL 存储过程返回多值
简介:在本教程中,您将学习如何开发返回多个值的存储过程。 MySQL存储函数只返回一个值。要开发返回多个值的存储程序,您需要使用存储过程
INOUT
或OUT
参数。
如果您不熟悉INOUT
或OUT
参数,请查看存储过程的参数教程以获取详细信息。
MySQL存储过程返回多个值的实例
我们来看看示例数据库中的orders
表。
+----------------+ | orders | +----------------+ | orderNumber | | orderDate | | requiredDate | | shippedDate | | status | | comments | | customerNumber | +----------------+ 7 rows in set (0.00 sec)以下存储过程接受客户编号,并返回发货(shipped),取消(canceled),解决(resolved)和争议(disputed)的订单总数。
DELIMITER $$ CREATE PROCEDURE get_order_by_cust( IN cust_no INT, OUT shipped INT, OUT canceled INT, OUT resolved INT, OUT disputed INT) BEGIN -- shipped SELECT count(*) INTO shipped FROM orders WHERE customerNumber = cust_no AND status = 'Shipped'; -- canceled SELECT count(*) INTO canceled FROM orders WHERE customerNumber = cust_no AND status = 'Canceled'; -- resolved SELECT count(*) INTO resolved FROM orders WHERE customerNumber = cust_no AND status = 'Resolved'; -- disputed SELECT count(*) INTO disputed FROM orders WHERE customerNumber = cust_no AND status = 'Disputed'; END $$ DELIMITER ;除
IN
参数外,存储过程还需要四个附加OUT
参数:shipped, canceled, resolved 和 disputed。在存储过程中,您使用SELECT
带有COUNT
函数的语句根据订单的状态获取相应的订单总数,并将其分配给相应的参数。
要使用get_order_by_cust
存储过程,请传递客户编号和四个用户定义的变量以获取输出值。
执行存储过程后,使用SELECT
语句输出变量值。
CALL get_order_by_cust(141,@shipped,@canceled,@resolved,@disputed); SELECT @shipped,@canceled,@resolved,@disputed;
+----------+-----------+-----------+-----------+ | @shipped | @canceled | @resolved | @disputed | +----------+-----------+-----------+-----------+ | 22 | 0 | 1 | 1 | +----------+-----------+-----------+-----------+ 1 row in set (0.00 sec)
使用PHP调用从返回多个值的存储过程
以下代码段显示如何调用从PHP返回多个值的存储过程。<?php /** * Call stored procedure that return multiple values * @param $customerNumber */ function call_sp($customerNumber) { try { $pdo = new PDO("mysql:host=localhost;dbname=classicmodels", 'root', ''); // execute the stored procedure $sql = 'CALL get_order_by_cust(:no,@shipped,@canceled,@resolved,@disputed)'; $stmt = $pdo->prepare($sql); $stmt->bindParam(':no', $customerNumber, PDO::PARAM_INT); $stmt->execute(); $stmt->closeCursor(); // execute the second query to get values from OUT parameter $r = $pdo->query("SELECT @shipped,@canceled,@resolved,@disputed") ->fetch(PDO::FETCH_ASSOC); if ($r) { printf('Shipped: %d, Canceled: %d, Resolved: %d, Disputed: %d', $r['@shipped'], $r['@canceled'], $r['@resolved'], $r['@disputed']); } } catch (PDOException $pe) { die("Error occurred:" . $pe->getMessage()); } } call_sp(141);用户定义的变量(以
@
符号开头)与数据库连接相关联,因此,它们可用于调用之间的访问。
在本教程中,我们向您展示了如何开发一个返回多个值的存储过程以及如何从PHP调用它。