根据mysql过程中的条件状态动态更改(ASC / DESC)排序数据

时间:2018-07-08 11:01:35

标签: mysql

当我声明一个游标时,它会根据此查询(ASC / DESC)对数据进行排序  我需要根据条件语句动态排序(ASC / DESC)。我的数据库系统是mysql。请帮助,我已经长期困扰这个问题了。

例如:

        DROP PROCEDURE IF EXISTS `updateStock`;
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `updateStock`(IN `ProductID` INT, IN `OrderQuantity` INT, IN `MethodType INT`, OUT `result_p` INT)
proc_label : BEGIN

declare TotalStock INT DEFAULT 0 ;

SET
  TotalStock =(
  SELECT
    SUM(a.QTY)
  FROM
    bf_inv_current_stock AS a
  WHERE
    a.MODEL_ID = ProductID
) ;

IF (TotalStock < OrderQuantity) THEN  
    LEAVE proc_label;      
END IF;

  begin
    declare InventoryID INT;
    declare QuantityInHand INT;
    declare v_finished INTEGER DEFAULT 0;
    declare getinventoryid_cursor cursor for  select id,qty from bf_inv_current_stock WHERE model_id = ProductID ORDER BY id ASC/DESC 

1 个答案:

答案 0 :(得分:1)

您可以将order by放在case中。

DECLARE getinventoryid_cursor CURSOR FOR
SELECT
    id, 
    qty 
FROM 
    bf_inv_current_stock 
WHERE model_id = ProductID 
ORDER BY 
    CASE WHEN methodType = 1 THEN id END ASC,
    CASE WHEN methodType = 0 THEN id END DESC

SQL Fiddle

您的过程中也有错误:

enter image description here