A SQL Server user-defined scalar function that allows replacing character repetitions, between minimum and maximum occurrences.
-- use <database_name>;
if exists(select * from sysobjects where name = 'fn_smart_replace')
begin
drop function fn_smart_replace;
print 'Success: UDF "fn_smart_replace" dropped.';
end;
go
-- ================================================================================================
-- Name: fn_smart_replace
-- Type: User Defined Scalar-valued Function
-- Description: Replace repeated sequences chars with length between a min and a max.
-- Dependencies: None
--
-- Parameters: @string = The string to perforn replace on.
-- @search_for = The substring to search for repetitions and replace.
-- @replace_with = The replacement value.
-- @min_replace_len = The min number of repetitions to replace.
-- @max_replace_len = The max number of repetions to replace.
--
-- Return Type: nvarchar(4000)
--
-- Usage: fn_smart_replace(@string, @search_for, @replace_with, @min_replace_len, @max_replace_len);
-- Example: select dbo.fn_smart_replace('This is an example of repeeeeeeeated chars.', 'e', '', 2, 6);
-- ================================================================================================
create function fn_smart_replace(
@string nvarchar(4000),
@search_for nvarchar(4000),
@replace_with nvarchar(4000),
@min_replace_len int = 1,
@max_replace_len int = 4000
)
returns nvarchar(4000)
with execute as caller
as
begin
declare @retval as nvarchar(4000);
declare @n as int;
set @retval = @string;
-- check if valid parameters passed
-- if not passthrough input value
if len(isnull(@string, '')) = 0 or len(isnull(@search_for, '')) = 0
begin
goto FUNC_EXIT;
end;
if @min_replace_len < 0
begin
set @min_replace_len = 0
end;
if @max_replace_len < @min_replace_len
begin
set @max_replace_len = @min_replace_len
end;
set @n = @max_replace_len;
while @n >= @min_replace_len
begin
set @retval = replace(@retval, replicate(@search_for, @n), @replace_with);
set @retval = replace(@retval, replicate(@replace_with, 2), @replace_with);
set @n = @n - 1;
end;
FUNC_EXIT:
return @retval;
end;
go
if exists(select * from sysobjects where type = 'FN'and name = 'fn_smart_replace')
begin
print 'Success: UDF "fn_smart_replace" created.';
end;
else
begin
print 'Failed: Could not create UDF "fn_smart_replace".';
end;
go