Extract email address from string using tsql

后端 未结 6 1472
面向向阳花
面向向阳花 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:30

    I know wewesthemenace already answered the question, but his/her solution seems over complicated. Why concatenate the left and right sides of the email address together? I'd rather just find the beginning and the end of the email address and then use substring to return the email address like so:

    My Table

    DECLARE @Table TABLE (comment NVARCHAR(50));
    INSERT INTO @Table
    VALUES ('blah MyEmailAddress@domain.org'),            --At the end
            ('blah MyEmailAddress@domain.org blah blah'), --In the middle
            ('MyEmailAddress@domain.org blah'),           --At the beginning
            ('no email');
    

    Actual Query:

    SELECT  comment,        
            CASE
                WHEN CHARINDEX('@',comment) = 0 THEN NULL
                ELSE SUBSTRING(comment,beginningOfEmail,endOfEmail-beginningOfEmail)
            END email
    FROM @Table
    CROSS APPLY (SELECT CHARINDEX(' ',comment + ' ',CHARINDEX('@',comment))) AS A(endOfEmail)
    CROSS APPLY (SELECT DATALENGTH(comment)/2 - CHARINDEX(' ',REVERSE(' ' + comment),CHARINDEX('@',REVERSE(' ' + comment))) + 2) AS B(beginningOfEmail)
    

    Results:

    comment                                            email
    -------------------------------------------------- --------------------------------------------------
    blah MyEmailAddress@domain.org                     MyEmailAddress@domain.org
    blah MyEmailAddress@domain.org blah blah           MyEmailAddress@domain.org
    MyEmailAddress@domain.org blah                     MyEmailAddress@domain.org
    no email                                           NULL
    

提交回复
热议问题