Version number sorting in Sql Server

前端 未结 7 1126
说谎
说谎 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条回答
  •  南笙
    南笙 (楼主)
    2021-01-13 06:36

    Implementation of Brain's Solution

    Declare @tblVersion table(VersionNumber varchar(100)) 
     Insert into @tblVersion Values('1.3.1') 
     Insert into @tblVersion Values('1.3.2.5') 
     Insert into @tblVersion Values('1.4.1.7.12') 
     Insert into @tblVersion Values('1.4.11.14.7') 
     Insert into @tblVersion Values('1.4.3.109.1') 
     Insert into @tblVersion Values('1.4.8.66') 
    
     --Select * From @tblVersion 
    
     ;With CTE AS
     (
        Select 
            Rn = Row_Number() Over(Order By (Select 1))
            ,VersionNumber
        From @tblVersion
    )
    ,CTESplit AS
    (
        SELECT 
                F1.Rn,
                F1.VersionNumber,
                VersionSort = 
                                Case 
                                        When Len(O.VersionSort) = 1 Then '000' + O.VersionSort
                                        When Len(O.VersionSort) = 2 Then '00' + O.VersionSort
                                        When Len(O.VersionSort) = 3 Then '0' + O.VersionSort
                                        When Len(O.VersionSort) = 4 Then O.VersionSort
                                End
    
        FROM
        (
            SELECT *,
            cast(''+replace(F.VersionNumber,'.','')+'' as XML) as xmlfilter from CTE F
        )F1
     CROSS APPLY
     ( 
        SELECT fdata.D.value('.','varchar(50)') as VersionSort  
        FROM f1.xmlfilter.nodes('X') as fdata(D)) O
     )
     ,CTE3 As(
    Select 
            --Rn 
            --,
            VersionNumber
            ,SortableVersion = 
                                Stuff(
                                        (Select '.' + Cast(VersionSort As Varchar(100))
                                 From CTESplit c2
                                 Where c2.Rn = c1.Rn
                                 For Xml Path('')),1,1,'')
    From CTESplit c1
    Group By c1.Rn,c1.VersionNumber
    )
    Select VersionNumber
    From CTE3
    Order By SortableVersion
    

提交回复
热议问题