SQL Server: ORDER BY parameters in IN statement

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

    What you could potentially do is:

    1. Create a TVF that would split string and keep original order.

    This questions seems to have this function already written: MS SQL: Select from a split string and retain the original order (keep in mind that there might be other approaches, not only those, covered in this question, I just gave it as an example to understand what function should do)

    So now if you'd run this query:

    SELECT *
    FROM dbo.Split('110,105,104,106', ',') AS T;
    

    It would bring back this table as a result.

    items rownum
    ------------
    110   1
    105   2
    104   3
    106   4
    

    Following that, you could simply query your table, join with this TVF passing your IDs as a parameter:

    SELECT P.ID, P.Name
    FROM Properties AS P
    INNER JOIN dbo.Split('110,105,104,106', ',') AS T
        ON T.items = P.ID
    ORDER BY T.rownum;
    

    This should retain order of parameters.

    If you need better performance, I'd advice to put records from TVF into hash table, index it and then join with actual table. See query below:

    SELECT T.items AS ID, T.rownum AS SortOrder
    INTO #Temporary
    FROM dbo.Split('110,105,104,106', ',') AS T;
    
    CREATE CLUSTERED INDEX idx_Temporary_ID
        ON #Temporary(ID);
    
    SELECT P.ID, P.Name
    FROM Properties AS P
    INNER JOIN #Temporary AS T
        ON T.ID = P.ID
    ORDER BY T.SortOrder;
    

    This should work better on larger data sets and equally well on small ones.

提交回复
热议问题