Split string in database row and copy results to different rows - SQL Server

前端 未结 3 1651
暗喜
暗喜 2021-01-16 14:58

I created an application to send mail to users. I\'m using a database where some users have more than one email address assigned.

Name                                


        
3条回答
  •  猫巷女王i
    2021-01-16 15:22

    The following is a UDF that I use to split values on an arbitrary delimiter. I've since modified my function so that it is an inline table function (instead of a multi-statement table function) and no longer relies on a Numbers table as it builds it on the fly.

    CREATE FUNCTION dbo.udf_Split
    (   
        @DelimitedList nvarchar(max)
        , @Delimiter nvarchar(2) = ','
    )
    RETURNS TABLE 
    AS
    RETURN 
        (
        With CorrectedList As
            (
            Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
                + @DelimitedList
                + Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
                As List
                , Len(@Delimiter) As DelimiterLen
            )
            , Numbers As 
            (
            Select Row_Number() Over ( Order By c1.object_id ) As Value
            From sys.columns As c1
                Cross Join sys.columns As c2
            )
        Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
            , Substring (
                        CL.List
                        , CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen     
                        , CharIndex(@Delimiter, CL.list, N.Value + 1)                           
                            - ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen ) 
                        ) As Value
        From CorrectedList As CL
            Cross Join Numbers As N
        Where N.Value < Len(CL.List)
            And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
        )
    

    Here's an example call:

    Select T.Name, Address.Value
    From MyTable As T
        Cross Apply dbo.udf_Split( T.Mail, ';' ) As Addresses
    

提交回复
热议问题