Extract email address from string using tsql

后端 未结 6 1427
面向向阳花
面向向阳花 2021-01-13 09:01

I\'m trying to extract email addresses from an existing comments field and put it into its own column. The string may be something like this \"this is an example comment wit

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-13 09:25

    You can search for '@' in the string. Then you get the string at the LEFT and RIGHT side of '@'. You then want to REVERSE the LEFT side and get first occurrence of ' ' then get the SUBSTRING from there. Then REVERSE it to get the original form. Same principle apply to the RIGHT side without doing REVERSE.

    Example string: 'some text someemail@domain.org some text'

    1. LEFT = 'some text someemail'
    2. RIGHT = '@domain.org some text'
    3. Reverse LEFT = 'liameemos txet emos'
    4. SUBSTRING up to the first space = 'liameemos'
    5. REVERSE(4) = someemail
    6. SUBSTRING (2) up to the first space = '@domain.org'
    7. Combine 5 and 6 = 'someemail@domain.org'

    Your query would be:

    ;WITH CteEmail(email) AS(
        SELECT 'someemail@domain.org' UNION ALL
        SELECT 'some text someemail@domain.org some text' UNION ALL
        SELECT 'no email'
    )
    ,CteStrings AS(
        SELECT
            [Left] = LEFT(email, CHARINDEX('@', email, 0) - 1),
            Reverse_Left = REVERSE(LEFT(email, CHARINDEX('@', email, 0) - 1)),
            [Right] = RIGHT(email, CHARINDEX('@', email, 0) + 1)
        FROM CteEmail
        WHERE email LIKE '%@%'
    )
    SELECT *,
        REVERSE(
            SUBSTRING(Reverse_Left, 0, 
                CASE
                    WHEN CHARINDEX(' ', Reverse_Left, 0) = 0 THEN LEN(Reverse_Left) + 1
                    ELSE CHARINDEX(' ', Reverse_Left, 0)
                END
            )
        )
        +
        SUBSTRING([Right], 0,
            CASE
                WHEN CHARINDEX(' ', [Right], 0) = 0 THEN LEN([Right]) + 1
                ELSE CHARINDEX(' ', [Right], 0)
            END
        )
    FROM CteStrings
    

    Sample Data:

    email
    ----------------------------------------
    someemail@domain.org
    some text someemail@domain.org some text
    no email
    

    Result

    ---------------------
    someemail@domain.org
    someemail@domain.org
    

提交回复
热议问题