GalloPinto
GalloPinto

Reputation: 677

Ordering rows when using IN on Microsoft SQL Server

I'm trying to get some SQL result from a list of ids. I have my ids ordered just as I need them, but when I pull the result from the query, the ids are not ordered as I need them.

enter image description here

I need the idParada ordered just as I sent them on the IN. I heard there is a order by FIELD on mysql but it doesn't not work for SQL Server.

Upvotes: 0

Views: 30

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1270713

Assuming you have SQL Server 2012+, use choose():

select *
from Paradas
where iparada in (21, 22, . . . )
order by choose(iparada, 21, 22, . . .);

Upvotes: 2

jarlh
jarlh

Reputation: 44796

Use a case to get your specific order:

select * from Paradas
where iparada in (21,22 ...)
order by case iparada when 21 then 1
                      when 22 then 2
                      ...
                   end

Upvotes: 0

Related Questions