我正在尝试在CASE
子句中使用ORDER BY
语句将行选择到临时表中,但是记录不会在插入时进行排序。
Declare @orderby varchar(10) , @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 = 'co1' then col1 end desc
declare @startrow int
declare @maxrows int
set @starrow = 19
set @maxrow = 30
set rowcount @maxrows
select * from #temp
where autoid > @startrow
答案 0 :(得分:1)
最坏的情况 - 您只需使用两个单独的SQL查询来实现目标:
if @direction = 'desc'
select identity (int) as autoid, *
into #temp
from table
order by col1 desc
if @direction = 'asc'
select identity (int) as autoid, *
into #temp
from table
order by col1 asc
答案 1 :(得分:0)
您可以使用#temp表而不是使用普通表temp来实现此目的。稍后当您完成流程后,您可以在最后删除它。
declare @dir varchar(10)='desc'
DECLARE @str varchar(1000)
SET @str='select identity (int) as autoid,
* into temp from cust1 order by TransactionType '+@dir
exec(@str)
select * from temp
答案 2 :(得分:0)
您需要在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