SQL Split Function and Ordering Issue?

后端 未结 5 1134
小鲜肉
小鲜肉 2021-01-18 03:53

I have the following Split function,

ALTER FUNCTION [dbo].[Split](@String varchar(8000), @Delimiter char(1))     
                returns @tempt         


        
5条回答
  •  滥情空心
    2021-01-18 04:41

    If you can abide compatibility level 130 of SQL Server, you can use the String_Split() function.

    With this and the Row_Number() function, you can return a table that includes the original sequence. For example:

    declare @Version nvarchar(128)
    set @Version = '1.2.3';
    
    with V as (select value v, Row_Number() over (order by (select 0)) n 
        from String_Split(@Version, '.')
    )
        select
            (select v from V where n = 1) Major,
            (select v from V where n = 2) Minor,
            (select v from V where n = 3) Revision
    

    Note that Row_Number requires an ordering, but if you pass a literal value the results are in the parsed sequence. This isn't guaranteed to be the case with future SQL Server version, as according to the String_Split documentation, there is no official ordering. I doubt Microsoft will break this, at least before introducing a version of the function that returns the order as it should, but in the mean time you best not depend on this ordering when writing code that decides whether or not to launch the missile.

    Returns:

    Major Minor Revision
    ----- ----- --------
    1     2     3
    

提交回复
热议问题