sql >> Base de Datos >  >> RDS >> Sqlserver

Cómo extraer múltiples cadenas de filas individuales en SQL Server

Puede usar un cte recursivamente para eliminar las cadenas.

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

Resultado

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