你需要使用多個排序條件,您的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
這絕對是毫無意義的嘗試,並插入到一個臨時表中特定的順序 - 當你想行早在一個特定的順序,你需要一個特定的'ORDER BY'反正.....所以你想達到什麼目標? – 2012-08-02 15:00:43
我想使用這個查詢分頁。我將從我的臨時表中選擇,我需要通過作爲參數傳入列的自動排序。我編輯了我的問題以獲得最終的選擇聲明。 – user1430949 2012-08-02 15:25:26
你可以從原始數據做到這一點 - 使用CTE和'ROW_NUMBER()' - 不需要將這些東西放到一個單獨的臨時表中,只需要分頁..... – 2012-08-02 15:27:13