Results 1 to 4 of 4

Thread: Sort query results by input

  1. #1

    Thread Starter
    Frenzied Member StrangerInBeijing's Avatar
    Join Date
    Mar 2005
    Location
    Not in Beijing
    Posts
    1,666

    Sort query results by input

    I wrote this query...the variables are just examples:
    Code:
    SELECT* FROM View_ChammVerPri 
    WHEREcharindex(VerID,'00101001,00201001,00101002')>0
    Can one modify the query, to sort the results by the order of the input variables?

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Sort query results by input

    To do that I think you'd need to use separate Select statements for each input, and Union them together.

    To do the sorting, add an extra value in the Select list (eg: "SELECT *, 1 as Sort_Order FROM"), then sort by that value.

  3. #3
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sort query results by input

    If this was a stored procedure I would fill a temporary table or table variable with the input selection - along with an "order column" for sorting. Then join to this table.

    What is your backend DB?

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  4. #4
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sort query results by input

    You might be able to actually order by that CHARINDEX value as well - have you tried that?

    ORDER BY charindex(VerID,'00101001,00201001,00101002')

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width