ORDER BY alphanumeric characters only in SQLite

后端 未结 5 1168
再見小時候
再見小時候 2021-02-05 15:24

I am sorting songs in SQLite (on Android). I want to order them:

  1. Case-insensitive
  2. With leading-digits at the end, by integer value.
  3. Without punct
5条回答
  •  一个人的身影
    2021-02-05 15:51

    If you're allowed to create functions, this is what I'd create (taken from How to strip all non-alphabetic characters from string in SQL Server? and modified a bit):

    Create Function [dbo].[RemoveNonAlphaNumericCharacters](@Temp VarChar(1000))
    Returns VarChar(1000)
    AS
    Begin
    
        Declare @KeepValues as varchar(50)
        Set @KeepValues = '%[^a-zA-Z0-9\s]%'
        While PatIndex(@KeepValues, @Temp) > 0
            Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')
    
        Return @Temp
    End
    

    This would meet your #3 requirement and strip all the junk out of your string, then your query would look like this:

    SELECT n
    FROM songs
    ORDER BY
      CASE WHEN [dbo].[RemoveNonAlphaNumericCharacters](name) GLOB '[0-9]*' THEN 1
           ELSE 0
      END,
      CASE WHEN [dbo].[RemoveNonAlphaNumericCharacters](name) GLOB '[0-9]*' THEN CAST(name AS INT)
           ELSE [dbo].[RemoveNonAlphaNumericCharacters](name)
      END
    COLLATE NOCASE
    

    It doesn't look pretty and might not have best performance. I'd probably do, what Stefan suggested. Parse your song names and insert trimmed ones into a separate column just for ordering (And of course have index on that column). It should be best solution.

提交回复
热议问题