T-SQL : How to get resultset in the the order of conditions with "in" query

  • Suppose i have table named as temp_OrderBy with the following structure

    name_id name_name

    ---------- ----------

    A1 John

    Ao Reymod

    Bc Kapil

    c01 Tang

    I want to query the table to get the records as is in my IN clause

    like :

    SELECT * FROM [dbo].[temp_OrderBy]

    WHERE name_name in ('Reymod','Tang','Kapil','John')

    Can anybody help in that..

    Thanks & Rgards,

    Sashikanta Mishra

  • Use a temp table instead of an IN statement and add a IDENTITY. You can JOIN both tables and use ORDER BY.

  • sashikanta.mishra (6/17/2009)


    SELECT * FROM [dbo].[temp_OrderBy]

    WHERE name_name in ('Reymod','Tang','Kapil','John')

    You could use a CASE statement as an ORDER BY clause:

    ORDER BY

    CASE

    WHEN name_name = 'Reymod' THEN 1

    WHEN name_name = 'Tang' THEN 2

    WHEN name_name = 'Kapil' THEN 3

    WHEN name_name = 'John' THEN 4

    END

    As you are specifying the 'IN' clause (either bt writing it directly or generating it from some input) it shouldn't be much extra effort to code the CASE statement as well.

    Cheers,

    Dave.

    Edit: Having read Florian's solution above, I reckon that's a better option than mine.

  • Thanks you guys..

    Both by Temp table and CASE statement works fine for me..

    Regards,

    Sashikanta Mishra

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply