你需要使用多个排序条件,您的ORDER BY子句来处理这个正常。这种方法的问题在于,如果由于那种令人讨厌的排序操作而导致表中有很多行,则性能会很差。
相反,使用动态SQL可能会更好(如其他人所建议的那样)。
Declare @orderby varchar(100) , @direction varchar(10)
set @orderby = 'col1'
set @direction = 'desc'
select identity (int) as autoid, *
into #temp
from table
order by case when @direction = 'desc' and @orderby = 'col1' then col1 end desc,
case when @direction = 'asc' and @orderby = 'col1' then col1 end,
case when @direction = 'desc' and @orderby = 'col2' then col2 end desc,
case when @direction = 'asc' and @orderby = 'col2' then col2 end,
case when @direction = 'desc' and @orderby = 'col3' then col3 end desc,
case when @direction = 'asc' and @orderby = 'col3' then col3 end,
case when @direction = 'desc' and @orderby = 'col4' then col4 end desc,
case when @direction = 'asc' and @orderby = 'col4' then col4 end,
case when @direction = 'desc' and @orderby = 'col5' then col5 end desc,
case when @direction = 'asc' and @orderby = 'col5' then col5 end
这绝对是毫无意义的尝试,并插入到一个临时表中特定的顺序 - 当你想行早在一个特定的顺序,你需要一个特定的'ORDER BY'反正.....所以你想达到什么目标? – 2012-08-02 15:00:43
我想使用这个查询分页。我将从我的临时表中选择,我需要通过作为参数传入列的自动排序。我编辑了我的问题以获得最终的选择声明。 – user1430949 2012-08-02 15:25:26
你可以从原始数据做到这一点 - 使用CTE和'ROW_NUMBER()' - 不需要将这些东西放到一个单独的临时表中,只需要分页..... – 2012-08-02 15:27:13