您可以遞歸地使用cte去除字符串。
declare @T table (id int, [text] nvarchar(max))
insert into @T values (1, 'Peter ([email protected]) and Marta ([email protected]) are doing fine.')
insert into @T values (2, 'Nothing special here')
insert into @T values (3, 'Another email address ([email protected])')
;with cte([text], email)
as
(
select
right([text], len([text]) - charindex(')', [text], 0)),
substring([text], charindex('(', [text], 0) + 1, charindex(')', [text], 0) - charindex('(', [text], 0) - 1)
from @T
where charindex('(', [text], 0) > 0
union all
select
right([text], len([text]) - charindex(')', [text], 0)),
substring([text], charindex('(', [text], 0) + 1, charindex(')', [text], 0) - charindex('(', [text], 0) - 1)
from cte
where charindex('(', [text], 0) > 0
)
select email
from cte
結果
email
[email protected]
[email protected]
[email protected]
我們可以假設數據中絕對沒有不平衡的括號嗎? – 2011-01-30 13:29:38
是的。我可以在以後處理這些錯誤,但需要一個可行的例子來繼續。在我現實世界的問題中,根本不是電子郵件地址,這只是爲了說明問題並創建一個小例子。 – Daniel 2011-01-30 13:32:28