Search code examples
sqldatabasesql-server-2005

How to get Result from database by order the condition put in "IN" clause?


Sorry for bad english.

bfproduct is a table and productid is primary key in this table and productname is another field defined in this table.

When i execute this query, select * from bfproduct where productid in (23,5,54,3132,32). The result is as follows:

 

productid | productname

5         15 Park Avenue
23        Good Boy Bad Boy
32        dsf sf gfdsf dsf d  
54       dsdsfsa ffs ff sfsf 
3132        Just Books - On The Failure of Legal System

Is there any way i will get the resultset in the order by the productid provided in "IN" Clause e.g.


productid | productname
23        Good Boy Bad Boy
5         15 Park Avenue
54       dsdsfsa ffs ff sfsf 
3132        Just Books - On The Failure of Legal System
32        dsf sf gfdsf dsf d  

Please help...


Solution

  • Here's one way to do it:

    SELECT *
    FROM bfproduct
    WHERE productid
    IN (23,5,54,3132,32)
    ORDER BY
       CASE productid
          WHEN   23 THEN 0
          WHEN    5 THEN 1
          WHEN   54 THEN 2
          WHEN 3132 THEN 3
          WHEN   32 THEN 4
       END