是否可以动态更改结果集列顺序?
伪代码示例:
select [city], [state], [country]
from mystuff
result order 2,1,3
这样结果集将是
state | city | country
California, LA, US
是否可以动态更改结果集列顺序?
伪代码示例:
select [city], [state], [country]
from mystuff
result order 2,1,3
这样结果集将是
state | city | country
California, LA, US
不,列顺序由 SELECT 列表确定。如果有一个查询由于某种原因必须保持完整,您可以将其用作派生表。例如:
SELECT [city], [state], [country]
FROM (fixedquery) as X
你可以试试下面的方法,它会帮助你...
询问 :
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
看看这个...