Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come estrarre più stringhe da singole righe in SQL Server

Puoi usare un cte in modo ricorsivo per rimuovere le stringhe.

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

Risultato

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