您需要在 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