I have a column with text/sentences that may include strings starting with ‘@’. I need to remove all strings starting with ‘@’ from the texts. For example:
Is there any function that can do the trick? I have tried the following but this removes only the ‘@’ from the string:
x
SELECT Column1,
LTRIM(SUBSTRING(Column1, CHARINDEX('@',Column1)+1, LEN(Column1))) AS [Output column]
FROM mytable
WHERE Column1 like '%@%';
Advertisement
Answer
One way to do it is with a recursive CTE:
with cte as (
select Column1 col, Column1 + ' ' Column1, 1 level from mytable
union all
select col,
left(Column1, charindex('@', Column1) - 1) +
right(Column1, len(Column1) - charindex(' ', Column1, charindex('@', Column1)) + 1),
level + 1
from cte
where charindex('@', Column1) > 0
)
select distinct rtrim(first_value(Column1) over (partition by col order by level desc)) Column1
from cte
See the demo.
Results:
> | Column1 |
> | :------------------------------------ |
> | another text text continues here word |
> | some text here text continue here |