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

最悪の場合、目的を達成するために 2 つの別個の 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テーブルを使用せずに実現できます。後でプロセスが終了したら、最後にドロップできます。

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 に答える