Другим подходом может быть использование рекурсивного CTE
, которое я узнал вчера из одного из ответов @Gordon Linoff.
;with cte as (
select v.input, convert(varchar(max), '') as updated, 1 as lev
from (values ('AVGHAHA')) v(input)
union all
select stuff(input, 1, 1, ''),
(case when charindex(left(input, 1),updated) > 0 then updated else concat(updated , left(input, 1)) end),
lev + 1
from cte
where input > ''
)
select top (1) with ties updated
from cte
order by row_number() over (order by lev desc);
Онлайн-демонстрация
Редактировать :
Как пользовательская функция.
CREATE FUNCTION dbo.Fn_Remove(@Input varchar(100))
RETURNS varchar(100)
AS
-- Returns the stock level for the product.
BEGIN
DECLARE @ret varchar(100)
;with cte as (
select v.input, convert(varchar(max), '') as updated, 1 as lev
from (values (@Input)) v(input)
union all
select stuff(input, 1, 1, ''),
(case when charindex(left(input, 1),updated) > 0 then updated else concat(updated , left(input, 1)) end),
lev + 1
from cte
where input > ''
)
select top (1) @ret=updated
from cte
order by lev desc
RETURN @ret;
END;