USE [PATIENT_DATA] GO Create function dbo.ReplaceCharsAsterisks(@Word varchar(max)) returns varchar(max) as begin declare @loop int = len(@word) while @loop > 1 select @word = stuff(@word, @loop, 1, case when substring(@word, @loop-1,2) like '% ' then ' ' when substring(@word, @loop-1,2) like ' %' then substring(@word, @loop,1) else '*' end), @loop+=-1 return @word; end