How to split string using delimiter char using T-SQL?

后端 未结 4 1326
无人及你
无人及你 2020-11-30 11:48

I have this long string in one of the columns of the table. I want to get only specific information:- My Table structure:-

Col1 = \'123\'
Col2 = \'AAAAA\'
Co         


        
4条回答
  •  执念已碎
    2020-11-30 12:30

    You need a split function:

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    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 TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) 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 <= DataLength(CL.List) / 2
            And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
        )
    

    With your split function, you would then use Cross Apply to get the data:

    Select T.Col1, T.Col2
        , Substring( Z.Value, 1, Charindex(' = ', Z.Value) - 1 ) As AttributeName
        , Substring( Z.Value, Charindex(' = ', Z.Value) + 1, Len(Z.Value) ) As Value
    From Table01 As T
        Cross Apply dbo.udf_Split( T.Col3, '|' ) As Z
    

提交回复
热议问题