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
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'
LEFT
= 'some text someemail'RIGHT
= '@domain.org some text'SUBSTRING
up to the first space = 'liameemos'REVERSE
(4) = someemailSUBSTRING
(2) up to the first space = '@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