您好,登錄后才能下訂單哦!
本篇文章為大家展示了怎么在mysql存儲過程中返回多個值,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
mysql存儲函數只返回一個值。要開發返回多個值的存儲過程,需要使用帶有INOUT或OUT參數的存儲過程。咱們先來看一個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, resolved 和 disputed。 在存儲過程中,使用帶有count函數的select語句根據訂單狀態獲取相應的訂單總數,并將其分配給相應的參數。按著上面的sql,我們如果要使用get_order_by_cust存儲過程,可以傳遞客戶編號和四個用戶定義的變量來獲取輸出值。執行存儲過程后,我們再使用SELECT語句輸出變量值:
+----------+-----------+-----------+-----------+ | @shipped | @canceled | @resolved | @disputed | +----------+-----------+-----------+-----------+ | 22 | 0 | 1 | 1 | +----------+-----------+-----------+-----------+ 1 row in set
結合實際應用,我們再來看下從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);
上述內容就是怎么在mysql存儲過程中返回多個值,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。