MYSQL:用户

时间:2017-06-07 05:24:17

标签: mysql sql-order-by

我有一张这样的表:

表:Cols

 col1   col2    col3    col4
------ ------  ------  -------
  1       2       5       8
  5       4       2       7
  5       3       7       4
  7       5       4       1

用户选择的排序列非常重要,我尝试类似:

    SELECT col1,Col2,Col3
    FROM Cols
    order by cast(:ORDER_ID_COL as integer)

    SELECT col1,Col2,Col3
    FROM Cols
    order by cast(:ORDER_ID_COL as varchar(20))

两者都没有错误但没有正确。

如果我不在路上,请赐教我回到正轨。

2 个答案:

答案 0 :(得分:2)

当您将:ORDER_ID_COL传递给sql时,它将被视为值而不是列,因此它不会产生您想要的顺序,换句话说,您的查询如下:

SELECT col1,Col2,Col3
FROM Cols
order by 'col1'

你可以用一种丑陋的方式来做到这一点:

SELECT col1,Col2,Col3
FROM Cols
order by case when :ORDER_ID_COL = 'col1' then col1
              when :ORDER_ID_COL = 'col2' then col2
              when :ORDER_ID_COL = 'col3' then col3
              when :ORDER_ID_COL = 'col4' then col4
         end

或者使用动态sql:

SET @sql = concat('select col1,Col2,Col3 from cols order by ', :ORDER_ID_COL);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

答案 1 :(得分:1)

尝试:::

DECLARE @OrderBy VARCHAR(10) = '/*Here, pass the column name(if multiple columns, pass column names separated by commas)*/'
DECLARE @SQLquery VARCHAR(MAX) = '    
SELECT col1,Col2,Col3
FROM Cols
order by ' + @OrderBy

EXEC (@SQLquery)