我在包含电子邮件地址的表格中有一个自由格式的文本字段。问题是该字段中有很多其他信息,在电子邮件地址之前和之后。 编辑:以下是该字段可能的示例:
Address: 123 Anystreet. Customer requires xyz. Email: person@example.com Other random info...
我认为尝试仅提取电子邮件地址的最佳方法是对@字符进行SQL搜索,并检索所有周围文本,直到找到空格。这可能吗?或者有更好的方法吗?
答案 0 :(得分:1)
这是一种方法
SELECT Email = Reverse(Substring(Reverse(string), revpos+1, Charindex(' ', Reverse(string), revpos)-revpos))
+ Substring(string, pos, Charindex(' ', string, pos)-pos)
FROM yourtable
CROSS apply(VALUES (Charindex('@', string)))tc(pos)
CROSS apply(VALUES (Charindex('@', Reverse(string))))tc1(revpos)
注意:
这假设有两件事
@
出现Email
总是被空格包围答案 1 :(得分:1)
基于答案at former question(2015年4月13日2:44由Stephan撰写) 请参阅此SQL Fiddle
CREATE TABLE Table1
([BigString] varchar(100))
;
INSERT INTO Table1
([BigString])
VALUES
('Address: 123 Anystreet. Customer requires xyz. Email: person@example.com Other random info...'),
('blah MyEmailAddress@domain.org'),
('blah MyEmailAddress@domain.org blah blah'),
('MyEmailAddress@domain.org blah'),
('no email')
;
查询1 :
select BigString, c3.email
from (
select BigString
from Table1
where CHARINDEX('@',BigString) > 0
) t
cross apply (select charindex('@',BigString)) c1 (atpos)
cross apply (select charindex(' ',BigString + ' ',c1.atpos), reverse(substring(BigString,1,c1.atpos))
) c2 (endOfEmail,RevString)
cross apply (select RTRIM(Reverse(left(RevString,charindex(' ',RevString+' ')-1))
+ substring(BigString,c1.atpos+1,endOfEmail-c1.atpos))
) c3 (email)
<强> Results 强>:
| BigString | email |
|-----------------------------------------------------------------------------------------------|---------------------------|
| Address: 123 Anystreet. Customer requires xyz. Email: person@example.com Other random info... | person@example.com |
| blah MyEmailAddress@domain.org | MyEmailAddress@domain.org |
| blah MyEmailAddress@domain.org blah blah | MyEmailAddress@domain.org |
| MyEmailAddress@domain.org blah | MyEmailAddress@domain.org |