What is the MS SQL Server capability similar to the MySQL FIELD() function?

前端 未结 4 1631
不知归路
不知归路 2020-12-09 17:44

MySQL provides a string function named FIELD() which accepts a variable number of arguments. The return value is the location of the first argument in the list of the remai

相关标签:
4条回答
  • 2020-12-09 18:26
    ORDER BY CHARINDEX(','+convert(varchar,status)+',' ,   
      ',rejected,active,submitted,approved,')
    
    
    just put a comma before and after a string in which you are finding the substring index or you can say that second parameter.
    
    and first parameter of charindex is also surrounded by ,  
    
    0 讨论(0)
  • 2020-12-09 18:36

    For your particular example your could:

    ORDER BY CHARINDEX(
        ',' + status + ',',
        ',rejected,active,submitted,approved,'
    )
    

    Note that FIELD was supposed to return 0, 1, 2, 3, 4 where as the above will return 0, 1, 10, 17 and 27 so this trick is only useful inside the order by clause.

    0 讨论(0)
  • 2020-12-09 18:39

    Use a CASE expression (SQL Server 2005+):

    ORDER BY CASE status
               WHEN 'active' THEN 1
               WHEN 'approved' THEN 2
               WHEN 'rejected' THEN 3
               WHEN 'submitted' THEN 4
               ELSE 5
             END
    

    You can use this syntax for more complex evaluation (including combinations, or if you need to use LIKE)

    ORDER BY CASE 
               WHEN status LIKE 'active' THEN 1
               WHEN status LIKE 'approved' THEN 2
               WHEN status LIKE 'rejected' THEN 3
               WHEN status LIKE 'submitted' THEN 4
               ELSE 5
             END
    
    0 讨论(0)
  • 2020-12-09 18:39

    I recommend a CTE (SQL server 2005+). No need to repeat the status codes or create the separate table.

    WITH cte(status, RN) AS (  -- CTE to create ordered list and define where clause
          SELECT 'active', 1
    UNION SELECT 'approved', 2
    UNION SELECT 'rejected', 3
    UNION SELECT 'submitted', 4
    )
    SELECT <field1>, <field2>
    FROM <table> tbl
    INNER JOIN cte ON cte.status = tbl.status  -- do the join
    ORDER BY cte.RN  -- use the ordering defined in the cte
    

    Good luck,

    Jason

    0 讨论(0)
提交回复
热议问题