2012-08-02 67 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