How to replace the first occurrence in a string in SQL Server

There might be times when you want to replace the first occurrence of a substring in a string, but the Replace command does every occurrence. It is possible to do this. Use the following function so that you can call it in the future.

Create Function ReplaceFirst(@String varchar(max), @Find varchar(1024), @Replace varchar(1024)) returns varchar(max)
Begin
    Return STUFF(@String, CHARINDEX(@Find, @string), LEN(@Find), @Replace)
end

Tags - SQL


About... / Contact.. / Cookie...