How to compare software versions using SQL Server?

后端 未结 16 2236
清酒与你
清酒与你 2020-12-03 07:30

When trying to compare software versions 5.12 to 5.8, version 5.12 is newer, however mathematically 5.12 is less than 5.8. How would I compare the two versions so that a new

16条回答
  •  余生分开走
    2020-12-03 08:20

    I have created (with inspiration from Eva Lacy (above)), this function:

    CREATE or alter function dbo.IsVersionNewerThan
    (
        @Source nvarchar(max),
        @Target nvarchar(max)
    )
    RETURNS table
    as 
    /*
    -1 : target has higher version number (later version)
    0 : same
    1 : source has higher version number (later version)
    
    test harness:
    ; WITH tmp
    AS
    (
        SELECT '1.0.0.5' AS Version
        UNION ALL SELECT '0.0.0.0'
        UNION ALL SELECT '1.5.0.6'
        UNION ALL SELECT '2.0.0'
        UNION ALL SELECT '2.0.0.0'
        UNION ALL SELECT '2.0.1.1'
        UNION ALL SELECT '15.15.1323.22'
        UNION ALL SELECT '15.15.622.55'
    )
    SELECT tmp.version, isGreather from tmp
    outer apply (select * from dbo.IsVersionNewerThan(tmp.Version, '2.0.0.0')) as IsG
    
    */ 
        return (
            select CASE 
                when cast('/' + @Source + '/' as hierarchyid) > cast('/' + @Target + '/' as hierarchyid) THEN 1 
                when @Source = @Target then 0
                else -1 
            end as IsGreather
        )
    go
    

    The test script is included as a comment. It works, as long as you do not have versions like '1.5.06.2' (note the zero).
    SQL Server thinks this function has is_inlineable = 1, which bodes well for the performance.

    Then my SQL code can look like this:

    declare @version varchar(10) = '2.30.1.12'
    set @version = '2.30.1.1'
    if exists(select * from dbo.IsVersionNewerThan(@version,'2.30.1.12') where IsGreather >= 0)
    BEGIN
        print 'yes'
    end
    else print 'no'
    

提交回复
热议问题