我正在尝试从数据库的用户表的 Email1 列中仅获取域名。
UserId Email1
1 abc@gmail.com
2 xyz@google.com
3 xyz@abc.com
4 abc@xyz.com
5 123@stackoverflow.com
当我运行此查询时:
SELECT LEFT( RIGHT(Email1, LEN(Email1)-CHARINDEX('@', Email1)),
CHARINDEX('.', RIGHT(Email1, LEN(Email1)-CHARINDEX('@', Email1))))
as EmailNamePart FROM Users
我得到以下信息:
gmail.
google.
abc.
xyz.
stackoverflow.
而预期结果应该是:
gmail
google
abc
xyz
stackoverflow
任何提示我的查询出了什么问题吗?
答案 0 :(得分:1)
根据您的评论”“在这种情况下,我将从“ @”中删除到第一个“”。 “” 这样可以为您提供追寻的东西,但不确定它是您真正想要的东西:
WITH VTE AS(
SELECT *
FROM (VALUES('abc@gmail.com'),
('xyz@google.com'),
('xyz@abc.com'),
('abc@xyz.com'),
('123@stackoverflow.com'),
('def@dba.stackexchange.com'),
('xx@msn.co.uk'),
('abc123@mail.yahoo.co.uk'))V(Email))
SELECT LEFT(D.Domain,CI.Extension-1) AS SubDomain
FROM VTE V
CROSS APPLY (VALUES(STUFF(V.Email, 1,CHARINDEX('@',Email),'')))D(Domain)
CROSS APPLY (VALUES(CHARINDEX('.',D.Domain)))CI(Extension);
输出:
SubDomain
-----------
gmail
google
abc
xyz
stackoverflow
dba
msn
mail
答案 1 :(得分:1)
尝试一下:
-如果只想第一个点-
select SUBSTRING(Email1, CHARINDEX('@', Email1)+1,
CHARINDEX('.', V.Email, CHARINDEX('@', Email1))-CHARINDEX('@', Email1)-1) as
EmailNamePart FROM Users
-如果要最后一个点-
select SUBSTRING(Email1, CHARINDEX('@', Email1)+1,
(charindex('.', reverse(Email1) + '0') - len(Email1))*-1-(CHARINDEX('@', Email1)))
as EmailNamePart FROM Users