SQL Server: ORDER BY parameters in IN statement

后端 未结 6 904
抹茶落季
抹茶落季 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:12

    Here is a solution that does not rely on hard codes values or dynamic sql (to eliminate hard coding values).

    I would build a table (maybe temp or variable) with OrderByValue and OrderBySort and insert from the application.

    OrderByValue OrderBySort
    110            1
    105            2
    104            3
    106            4
    

    Then I would join on the value and sort by the sort. The join will be the same as the In clause.

    SELECT A.ID, A.Name 
       FROM Properties A 
       JOIN TempTable B On A.ID = B.OrderByValue
       Order By B.OrderBySort
    

提交回复
热议问题