2013-10-15 115 views
0

說我有下列名稱和逗號列表分隔的電子郵件地址:SQL分裂電子郵件數據分隔的電子郵件地址

SELECT 'a' name, '[email protected], [email protected]' email INTO #Temp UNION ALL 
SELECT 'b', '[email protected]' UNION ALL 
SELECT 'c', '[email protected], [email protected], [email protected]' 

SELECT * FROM #temp 

是否可以選擇每個電子郵件地址的行?

a [email protected] 
a [email protected] 
b [email protected] 
c [email protected] 
c [email protected] 
c [email protected] 

回答

3

請嘗試:

SELECT A.name, 
    Split.a.value('.', 'VARCHAR(100)') AS CVS 
FROM 
(
    SELECT name, 
     CAST ('<M>' + REPLACE(email, ',', '</M><M>') + '</M>' AS XML) AS CVS 
    FROM #Temp 
) AS A CROSS APPLY CVS.nodes ('/M') AS Split(a) 
+0

謝謝,就像一個魅力...只是不會忽略加了LTRIM(RTRIM()) – woggles

+0

小心'VARCHAR(100) ' - 根據標準IIRC,電子郵件地址可以是320個字符。 –

+0

@AaronBertrand - 程序問題 - RFC已經通過錯誤說明最大長度爲254個字符 - 請參閱http://stackoverflow.com/questions/386294/what-is-the-maximum-length-of - 有效的電子郵件地址 - 但你的觀點依然存在 –