0

我正在尝试使用子句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
4

3 回答 3

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
于 2012-08-02T15:44:12.317 回答
1

您需要在 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
于 2012-08-02T19:00:55.330 回答
0

您可以不使用 #temp 表 insted 使用普通表临时来实现此目的。稍后当你完成你的过程时,你可以在最后放弃它。

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
于 2012-08-02T15:40:15.687 回答