Get string between 2 characters that repeats several times in sql server

后端 未结 4 1469
执笔经年
执笔经年 2021-01-21 22:58

I need to extract multiple strings between 2 specific characters that repeats several times in a row. for example; these are 2 rows from my table:

id myString
         


        
4条回答
  •  無奈伤痛
    2021-01-21 23:45

    I know I'm coming very late to the party, but I ran into the exact same problem, and found a very easy way to complete it with a recursive CTE.

    I hope this is helpful to anyone running into the same issue.

    IF OBJECT_ID('tempdb..#Temp') IS NOT NULL DROP TABLE #Temp
    CREATE TABLE #Temp (
        [ID]    INT,
        [Text]  VARCHAR(255)
    )
    
    INSERT INTO #Temp ([ID], [Text])
    VALUES (1, '(test1) sdkjsdlfnicsn */12e3mdsf ksd (test 2) $#@ewmfdsdk (test3)'), (2, '(test4) sdvdsg */sdg ksd (test 5) $#@ewmfdsdk (test6)(test7)')
    
    ;WITH CTE AS (
        SELECT [x].[ID], [x].[Text], [x].[OpenBraket], [x].[CloseBraket]
        ,SUBSTRING([x].[Text], ([x].[OpenBraket] + 1), ([x].[CloseBraket] - [x].[OpenBraket] - 1)) AS [Value]
        ,SUBSTRING([x].[Text], ([x].[CloseBraket] + 1), (LEN([Text]) - [x].[CloseBraket])) AS [RemainingText]
        FROM (
            SELECT [ID], [Text]
                ,CHARINDEX('(', [Text]) AS [OpenBraket]
                ,CHARINDEX(')', [Text]) AS [CloseBraket]        
            FROM #Temp
            WHERE [Text] LIKE '%(%)%'
        ) x
    
        UNION ALL
    
        SELECT [z].[ID], [z].[Text], [z].[OpenBraket], [z].[CloseBraket]
            ,SUBSTRING([z].[RemainingText], ([z].[OpenBraket] + 1), ([z].[CloseBraket] - [z].[OpenBraket] - 1)) AS [Value]
            ,SUBSTRING([z].[RemainingText], ([z].[CloseBraket] + 1), (LEN([RemainingText]) - [z].[CloseBraket])) AS [RemainingText]
        FROM (
            SELECT [ID], [Text], [RemainingText]
                ,CHARINDEX('(', [RemainingText]) AS [OpenBraket]
                ,CHARINDEX(')', [RemainingText]) AS [CloseBraket]
            FROM [CTE]
            WHERE [RemainingText] LIKE '%(%)%'
        ) z
    )
    
    SELECT [ID], [Value] FROM CTE
    

提交回复
热议问题