mysql存储过程动态顺序由混合类型组成

时间:2011-08-25 05:57:42

标签: mysql sql stored-procedures

我正在创建一个存储过程,我正在动态地传递“订单”:

CREATE PROCEDURE `getStuff`(IN orderSQL VARCHAR(100))
BEGIN
    SELECT id, name, createdate
    FROM mytable
    ORDER BY
        CASE WHEN orderSQL='id_desc' THEN CONCAT(id, '') END DESC,
        CASE WHEN orderSQL='id_asc' THEN CONCAT(id, '') END ASC,
        CASE WHEN orderSQL='name_desc' THEN name END DESC,
        CASE WHEN orderSQL='name_asc' THEN name END ASC,
        CASE WHEN orderSQL='date_desc' THEN CONCAT(createdate, '') END DESC,
        CASE WHEN orderSQL='date_asc' THEN CONCAT(createdate, '') END ASC
END

正如您所看到的,我正在使用CONCAT将所有非VARCHAR字段转换为VARCHAR,因为混合可能的订单类型不会像http://www.4guysfromrolla.com/webtech/010704-1.shtml中所解释的那样工作。

我的问题是现在通过名称排序有效,但非字符串顺序返回为1,10,11,2,3,4,5,6,7,8,9。等

有没有办法使用混合数据类型动态排序,仍然按正确的顺序返回整数,日期等。

2 个答案:

答案 0 :(得分:5)

解决方案是动态创建SQL语句,如此

DELIMITER $$

CREATE PROCEDURE GetStuff (IN orderSQL varchar(100) ) 
BEGIN

  DECLARE SQLStatement varchar(255);

  -- Enter the dynamic SQL statement into the
  -- variable @SQLStatement
  SET SQLStatement = CONCAT('SELECT id, name, createdate ',
                             'FROM mytable ',
                             'ORDER BY ',orderSQL);

  PREPARE stmt FROM SQLStatement;
  EXECUTE stmt;
END $$

DELIMITER ;

有关详细信息,请参阅此处:http://rpbouman.blogspot.com/2005/11/mysql-5-prepared-statement-syntax-and.html

答案 1 :(得分:2)

您应该使用prepared statements来构建和执行自定义查询,或者您应该使用所有查询编写大CASE条件,即 -

  CASE orderSQL
    WHEN 'id_desc' THEN
      SELECT id, name, createdate FROM mytable ORDER BY id;
    WHEN 'id_desc' THEN
      SELECT id, name, createdate FROM mytable ORDER BY id_desc;
    ...
    ...
    ...
  END CASE;