Reputation: 1421
I need help in ordering my resultset of SQL Server 2005. My Query is
Select RQuery from EPMaster where PName IN ('PFNAME','POName','PFSName');
The result shown is in order as stored in the table EPMaster
In the table EPMaster, the order for values of PName are:
PFName -> 1
PFSName -> 2
POName -> 3
1 being the topmost and 3 being lowest
I need the results in order of the passed parameters of the query made with IN
. It means that the result should be in the form
PFName -> 1
POName -> 2
PFsName -> 3
Upvotes: 0
Views: 91
Reputation: 882226
Select
does not guarantee any sort of order unless you specify an order by
clause.
For your particular case, you can use something like:
... order by (case when PName = 'PFSName' then 'ZZZZZ' else PName end ) asc
but you should be aware that this sort of query may be a performance killer.
If your query is created dynamically, and you have no control over the order in which the possibilities are given, yet still want to dictate that the rows are in the same order, you may have to resort to building your query differently, such as with:
select 1 as xyzzy, RQuery from EPMaster where PName = 'PFNAME'
union all
select 2 as xyzzy, RQuery from EPMaster where PName = 'POName'
union all
select 3 as xyzzy, RQuery from EPMaster where PName = 'PFSName'
order by 1 asc
If your code builds this query rather than the in
vesrsion, you can guarantee that the rows will be returned in the order as specified, because of the xyzzy
column you add (and sort by).
Upvotes: 2
Reputation: 300728
Select RQuery from EPMaster
where PName IN ('PFNAME','POName','PFSName')
order by case when PName = 'PFName' then 0
when PName = 'POName' then 1
when PName = 'PFsName' then 2
else 999
end asc
An alternative and often used solution is to add an OrderBy column to a FK lookup table (Pname).
Upvotes: 0