sqlsql-serversql-server-2012

Replace first occurrence of substring in a string in SQL


I have to fetch data from a @temp table which has something like "or ccc or bbb or aaa" I want to replace the first occurrence into space to get something like this " ccc or bbb or aaa". I am trying stuff and replace but they don't seem to get me the desired result

What I have tried:

DECLARE @stringhere as varchar(500)

DECLARE @stringtofind as varchar(500)

set @stringhere='OR contains or cccc or  '

set @stringtofind='or'
select STUFF('OR contains or cccc or  ',PATINDEX('or', 'OR contains or cccc or  '),0 ,' ')

Solution

  • You can use a combination of STUFF and CHARINDEX to achieve what you want:

    SELECT STUFF(col, CHARINDEX('substring', col), LEN('substring'), 'replacement')
    FROM #temp
    

    CHARINDEX('substring', col) will return the index of the first occurrence of 'substring' in the column. STUFF then replaces this occurrence with 'replacement'.