How to SORT in order as entered in SQL Server?

前端 未结 5 804
猫巷女王i
猫巷女王i 2020-12-04 00:44

I\'m using SQL Server and I\'m trying to find results but I would like to get the results in the same order as I had input the conditions.

My code:

S         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 01:28

    I will offer one more approach I just found out, but this needs v2016. Regrettfully the developers forgot to include the index into the resultset of STRING_SPLIT(), but this would work and is documented:

    A solution via FROM OPENJSON():

    DECLARE @str VARCHAR(100) = 'val1,val2,val3';
    
    SELECT *
    FROM OPENJSON('["' +  REPLACE(@str,',','","') + '"]');
    

    The result

    key value   type
    0   val1    1
    1   val2    1
    2   val3    1
    

    The documentation tells clearly:

    When OPENJSON parses a JSON array, the function returns the indexes of the elements in the JSON text as keys.

提交回复
热议问题