MySQL儲存過程返回多個值

2019-10-16 22:56:26

在本教學中,您將學習如何編寫/開發返回多個值的儲存過程。

MySQL儲存函式只返回一個值。要開發返回多個值的儲存過程,需要使用帶有INOUTOUT引數的儲存過程。

如果您不熟悉INPUTOUT引數的用法,請檢視儲存過程引數教學的詳細資訊。

返回多個值的儲存過程範例

我們來看看範例資料庫(yiibaidb)中的orders表。

mysql> desc orders;
+----------------+-------------+------+-----+---------+-------+
| Field          | Type        | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| orderNumber    | int(11)     | NO   | PRI | NULL    |       |
| orderDate      | date        | NO   |     | NULL    |       |
| requiredDate   | date        | NO   |     | NULL    |       |
| shippedDate    | date        | YES  |     | NULL    |       |
| status         | varchar(15) | NO   |     | NULL    |       |
| comments       | text        | YES  |     | NULL    |       |
| customerNumber | int(11)     | NO   | MUL | NULL    |       |
+----------------+-------------+------+-----+---------+-------+
7 rows in set

以下儲存過程接受客戶編號,並返回發貨(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

IN引數之外,儲存過程還需要4個額外的OUT引數:shipped, canceled, resolveddisputed。 在儲存過程中,使用帶有COUNT函式SELECT語句根據訂單狀態獲取相應的訂單總數,並將其分配給相應的引數。

要使用get_order_by_cust儲存過程,可以傳遞客戶編號和四個使用者定義的變數來獲取輸出值。

執行儲存過程後,使用SELECT語句輸出變數值。

+----------+-----------+-----------+-----------+
| @shipped | @canceled | @resolved | @disputed |
+----------+-----------+-----------+-----------+
|       22 |         0 |         1 |         1 |
+----------+-----------+-----------+-----------+
1 row in set

從PHP呼叫返回多個值的儲存過程

以下程式碼片段顯示如何從PHP程式中呼叫返回多個值的儲存過程。

<?php
/**
 * Call stored procedure that return multiple values
 * @param $customerNumber
 */
function call_sp($customerNumber)
{
    try {
        $pdo = new PDO("mysql:host=localhost;dbname=yiibaidb", 'root', '123456');

        // 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呼叫它。