2017-08-31 66 views
2

我在員工表中的電子郵件列值:拆分郵件列到三列在SQL服務器

Email 
[email protected] 
[email protected] 
[email protected] 

我想要的電子郵件分成三列,如:

FirstName  LastName    DomainName 
-------------------------------------------------- 
regan   manning    @cresa.com 
miang   luso     @praxis.com 
selin   robert    @cummins.com 
+10

醜陋的問題。像「jon.m.skeet @ google.co.uk」這樣的邊緣案例呢? –

+0

什麼是SQL Server版本? –

+1

以及如果電子郵件以姓氏而不是名字開頭,該怎麼辦? – GuidoG

回答

2

一方法使用apply

select t.*, v.domain, v2.firstname, v2.lastname 
from t cross apply 
    (values(stuff(email, 1, charindex('@', email), '') as domain, 
      left(email, charindex('@', email) 
      ) 
    ) v(domain, name) cross apply 
    (values (left(name, charindex('.')), 
       stuff(name, 1, charindex('.', name), '') 
      ) 
    ) v2(lastname, firstname; 
+0

我想要它使用substring& charindex ...會üPLZ更新我的查詢... – Synergy

0
SELECT 

substring(@email , 0 , CHARINDEX('.' , @email)) , 

substring(@email , CHARINDEX('.',@email)+1 , CHARINDEX('@' , @email) - CHARINDEX('.' , @email)-1), 

substring(@email , CHARINDEX('@' , @email) , LEN(@email) - CHARINDEX('@' , @email)+1) 

from employee; 

與您的電子郵件列名

更簡單版本--replace @email明白:

DECLARE @email NVARCHAR(30) = '[email protected]'; 
DECLARE @dot INT =CHARINDEX('.' , @email); 
DECLARE @atrate INT =CHARINDEX('@' , @email); 
DECLARE @len INT =LEN(@email); 

SELECT 
substring(@email , 0 , @dot), 
substring(@email , @dot+1 , @atrate - @dot-1), 
substring(@email, @atrate , @len - @atrate+1); 
0

使用Substring & Charindex功能檢查.@ &檢索數據:

SELECT @email [Email], 
     SUBSTRING(@email, 1, CHARINDEX('.', @email)-1) [FirstName], 
     SUBSTRING(@email, CHARINDEX('.', @email)+1, CHARINDEX('@', @email)-CHARINDEX('.', @email)-1) [LastName], 
     SUBSTRING(@email, CHARINDEX('@', @email), LEN(@email)) [DomainName] from <table_name>; 

結果:

Email     FirstName LastName DomainName 
[email protected] miang  luso  @praxis.com