Version number sorting in Sql Server

前端 未结 7 1120
说谎
说谎 2021-01-13 05:35

I have a table that stores the versions as under

Declare @tblVersion table(VersionNumber varchar(100))
 Insert into @tblVersion Values(\'1.3.1\')
 Insert int         


        
7条回答
  •  -上瘾入骨i
    2021-01-13 06:21

    If you are on SQL Server 2005 or later and the number of possible fields in version numbers is fixed, you could try the following approach:

    SELECT t.*
    FROM @tblVersion t
      CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber,        1), 0)) v1
      CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v1.v + 1), 0)) v2
      CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v2.v + 1), 0)) v3
      CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v3.v + 1), 0)) v4
      CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v4.v + 1), 0)) v5
    ORDER BY
      CAST(SUBSTRING(t.VersionNumber, v1.v, v2.v - v1.v - 1) AS int),
      CAST(SUBSTRING(t.VersionNumber, v2.v, v3.v - v2.v - 1) AS int),
      CAST(SUBSTRING(t.VersionNumber, v3.v, v4.v - v3.v - 1) AS int),
      CAST(SUBSTRING(t.VersionNumber, v4.v, v5.v - v4.v - 1) AS int),
      CAST(SUBSTRING(t.VersionNumber, v5.v, 999) AS int)
    

    All fields of a version number are extracted one by one and converted to integers, which are then used for sorting. (Basically, @Brian's idea, as it turns out.)

提交回复
热议问题