2013-04-03 38 views
-1

是否可以動態更改結果集列順序?TSQL:動態更改選擇結果列順序

的僞代碼示例:

select [city], [state], [country] 
from mystuff 
result order 2,1,3 

使得結果集將是

state | city | country 
California, LA, US 
+0

@ user1939553:我已經添加了一個查詢作爲答案嘗試它... – Pandian

回答

1

,列順序由SELECT列表來確定。如果出於某種原因必須保持完整的查詢,則可以將其用作派生表。例如:

SELECT [city], [state], [country] 
FROM (fixedquery) as X 
0

你可以試試下面一樣,它會幫助你...

查詢:

Declare @order as varchar(100), @Query varchar(1000), @Query2 varchar(1000) 
set @order = 123 

While len(@order) > 0 
begin 
     set @Query = IsNull(@Query,'') + 
           case substring(@order, 1,1) 
            when 1 then 'city' 
            when 2 then 'state' 
            when 3 then 'country' 
           end + 
           Case when len(@order) > 1 then ',' else '' end 
     set @order = substring(@order, 2,len(@order)) 
end 

set @Query2 = 'select ' + @Query + ' from mystuff' 

Exec (@Query2) 

輸出:

If you give order as 123 then 

City -- State -- Country as result  

If you give order as 213 then 

State -- City --Country as result 

If you give order as 231 then 

State -- Country -- City as result 

檢查它出...