Extract email address from string using tsql

后端 未结 6 1425
面向向阳花
面向向阳花 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条回答
  •  一向
    一向 (楼主)
    2021-01-13 09:26

    For strings that contain new line characters I modified Felix's answer using PATINDEX to search for the first control character rather than white space.

    I also had to modify the Right field to subtract the correct amount of text.

        WITH CteEmail(email) AS(
            SELECT 'example string with new lines
    
        Email: some.example@email.address.com
    (first email address - should be returned)
    
        Email: another@test.co.uk
    (other email addresses should be ignored
    
    more example text' UNION ALL
            SELECT 'Email: some.example@email.address.com' UNION ALL
            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, LEN(email) - CHARINDEX('@', email, 0) + 1 )
            FROM CteEmail
            WHERE email LIKE '%@%'
        )
        SELECT *,
            REVERSE(
                SUBSTRING(Reverse_Left, 0, 
                    CASE
                        WHEN PATINDEX('%[' + CHAR(10)+'- ]%', Reverse_Left) = 0 THEN LEN(Reverse_Left) + 1
                        ELSE PATINDEX('%[' + CHAR(0)+'- ]%', Reverse_Left)
                    END
                )
            )
            +
            SUBSTRING([Right], 0,
                CASE
                    WHEN PATINDEX('%[' + CHAR(0)+'- ]%', [Right]) = 0 THEN LEN([Right]) + 1
                    ELSE PATINDEX('%[' + CHAR(0)+'- ]%', [Right])
                END
            )
        FROM CteStrings
    

提交回复
热议问题