SQL Server: ORDER BY parameters in IN statement

后端 未结 6 943
抹茶落季
抹茶落季 2020-12-21 19:38

I have a SQL statement that is the following:

SELECT A.ID, A.Name 
FROM Properties A 
WHERE A.ID IN (110, 105, 104, 106)

When I run this SQ

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-21 20:02

    Another solution for this problem is prepare a temporary table for IN clause like

    declare @InTable table (ID int, SortOrder int not null identity(1,1));
    

    We can fill this temp table with your data in order you want

    insert into @InTable values (110), (105), (104), (106);
    

    At last we need to modify your question to use this temp table like this

    select A.ID, A.Name 
    from Properties A 
    inner join @InTable as Sort on A.ID = Sort.ID
    order by Sort.SortOrder
    

    On the output you can see this

    ID  Name
    110 South
    105 East
    104 West
    106 North
    

    In this solution you don't need to provide order in special way. You just need to insert values in order you want.

提交回复
热议问题