另一种方法可以使用递归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);
Online Demo
编辑:
作为用户定义的函数。
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;