本篇文章为大家展示了怎么在mysql存储过程中返回多个值,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

mysql存储函数只返回一个值。要开发返回多个值的存储过程,需要使用带有INOUT或OUT参数的存储过程。咱们先来看一个orders表它的结构:

mysql>descorders;+----------------+-------------+------+-----+---------+-------+|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||+----------------+-------------+------+-----+---------+-------+7rowsinset

然后嘞,咱们来看一个存储过程,它接受客户编号,并返回发货(shipped),取消(canceled),解决(resolved)和争议(disputed)的订单总数:

DELIMITER$$CREATEPROCEDUREget_order_by_cust(INcust_noINT,OUTshippedINT,OUTcanceledINT,OUTresolvedINT,OUTdisputedINT)BEGIN--shippedSELECTcount(*)INTOshippedFROMordersWHEREcustomerNumber=cust_noANDstatus='Shipped';--canceledSELECTcount(*)INTOcanceledFROMordersWHEREcustomerNumber=cust_noANDstatus='Canceled';--resolvedSELECTcount(*)INTOresolvedFROMordersWHEREcustomerNumber=cust_noANDstatus='Resolved';--disputedSELECTcount(*)INTOdisputedFROMordersWHEREcustomerNumber=cust_noANDstatus='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|+----------+-----------+-----------+-----------+1rowinset

结合实际应用,我们再来看下从PHP程序中调用返回多个值的存储过程:

<?php/***Callstoredprocedurethatreturnmultiplevalues*@param$customerNumber*/functioncall_sp($customerNumber){try{$pdo=newPDO("mysql:host=localhost;dbname=yiibaidb",'root','123456');//executethestoredprocedure$sql='CALLget_order_by_cust(:no,@shipped,@canceled,@resolved,@disputed)';$stmt=$pdo->prepare($sql);$stmt->bindParam(':no',$customerNumber,PDO::PARAM_INT);$stmt->execute();$stmt->closeCursor();//executethesecondquerytogetvaluesfromOUTparameter$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("Erroroccurred:".$pe->getMessage());}}call_sp(141);

上述内容就是怎么在mysql存储过程中返回多个值,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。