2012-08-02 69 views
0

我试图用ORDER BY子句中的CASE语句将行选入临时表中,但记录未在插入时排序。SQL Server 2000:按条件排序时的选择

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 
+1

这绝对是毫无意义的尝试,并插入到一个临时表中特定的顺序 - 当你想行早在一个特定的顺序,你需要一个特定的'ORDER BY'反正.....所以你想达到什么目标? – 2012-08-02 15:00:43

+0

我想使用这个查询分页。我将从我的临时表中选择,我需要通过作为参数传入列的自动排序。我编辑了我的问题以获得最终的选择声明。 – user1430949 2012-08-02 15:25:26

+0

你可以从原始数据做到这一点 - 使用CTE和'ROW_NUMBER()' - 不需要将这些东西放到一个单独的临时表中,只需要分页..... – 2012-08-02 15:27:13

回答

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 '[email protected] 
exec(@str) 
select * from temp 
+0

因为他使用SQL Server 2000,所以这是** NOT **一个有效的选项(参见最后的评论) – 2012-08-02 15:40:37

+0

噢耶我没有看到他最后的评论。我想知道这在SQL 2000 – AnandPhadke 2012-08-02 15:42:32

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 
+0

临时表可以按六列进行排序,并且每个都可以排序为asc或desc。我不认为我想要写12个单独的查询。 – user1430949 2012-08-02 15:50:24

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