下面是一个订单取消的含2个游标的存储过程
set ANSI_NULLS ONset QUOTED_IDENTIFIER ONgoALTER PROCEDURE [dbo].[CancelOrderBySystem]ASBEGINdeclare /*声明变量*/@Status varchar(100), --状态@TimeNow datetime, --当前时间@TradeID varchar(50), --订单单号@GoodsID int, --商品ID@Num int, --数量@SkuID int --规格IDset @Status='TRADE_CLOSED_BY_SYSTEM' /*为变量赋值*/set @TimeNow=getdate() begin transaction; --开始执行事务--查询所有已过期的订单--对于已过期的订单查询其子订单,判断订单是否有规格--如果没有规格的需先判断现在的是否有规格,有则不改总库存--如果有规格的先判断该规格释放存在,存在才释放规格库存和总库存--修改订单的状态declare cancelOrder_Cursor cursor for --声明游标select TradeID from WxTrade where Status='WAIT_BUYER_PAY' and OutTime<=@TimeNow OPEN cancelOrder_Cursor --打开游标FETCH NEXT FROM cancelOrder_Cursor --获取游标的下一行数据into @TradeID --使变量获得当前游标指定行的订单单号 ----------------------外部游标(主订单)begin --------------------------WHILE (@@FETCH_STATUS = 0) --FETCH语句执行成功BEGIN --修改订单的状态 update WxTrade set Status=@Status,CloseTime=@TimeNow where TradeID=@TradeID --修改总库存和规格库存,对于已过期的订单查询其子订单 declare orderDetail_Cursor cursor for --声明游标 select GoodsID,SkuID,Num from WxOrder where TradeID=@TradeID OPEN orderDetail_Cursor --打开游标(子订单) FETCH NEXT FROM orderDetail_Cursor --获取游标的下一行数据 into @GoodsID,@SkuID,@Num --使变量获得当前游标指定行的商品ID,规格ID,数量 ----------------------内部嵌套游标(子订单)begin ---------------------- ------------------------------------------------------------------------ WHILE (@@FETCH_STATUS = 0) --FETCH语句执行成功 BEGIN if(@SkuID is null) BEGIN --没有规格的需先判断现在的是否有规格,有则不改总库存,没有则改 if not exists(select SkuID from [Sku] where GoodsID=@GoodsID) BEGIN update Goods set Quantity=Quantity+@Num where GoodsID=@GoodsID END END else BEGIN --如果有规格的先判断该规格是否存在,存在才释放规格库存和总库存 if exists(select SkuID from [Sku] where SkuID=@SkuID) BEGIN update [Sku] set ItemQuantity=ItemQuantity+@Num where SkuID=@SkuID update Goods set Quantity=Quantity+@Num where GoodsID=@GoodsID END END FETCH NEXT FROM orderDetail_Cursor --获取游标的下一行(子订单) into @GoodsID,@SkuID,@Num --使变量获得当前游标指定行的商品ID,规格ID,数量 END CLOSE orderDetail_Cursor --关闭游标(子订单) DEALLOCATE orderDetail_Cursor --释放游标(子订单) ----------------------内部嵌套游标(子订单)end ---------------------- ---------------------------------------------------------------------- FETCH NEXT FROM cancelOrder_Cursor --获取游标的下一行(主订单) into @TradeID --使变量获得当前游标指定行的订单单号EndCLOSE cancelOrder_Cursor --关闭游标(主订单)DEALLOCATE cancelOrder_Cursor --释放游标(主订单) ----------------------外部游标(主订单)end --------------------------if(@@error>0) begin rollback transaction return 0 endelse begin commit transaction return 1 endEND
参考:http://blog.csdn.net/gxiangzi/article/details/6774786#0-qzone-1-7441-d020d2d2a4e8d1a374a433f596ad1440
http://blog.csdn.net/superhoy/article/details/7663542#0-qzone-1-15425-d020d2d2a4e8d1a374a433f596ad1440
新闻热点
疑难解答