Replace first occurrence of substring in a string in SQL

后端 未结 4 864
粉色の甜心
粉色の甜心 2020-11-30 13:25

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

相关标签:
4条回答
  • 2020-11-30 14:02

    You can do a CHARINDEX or a PATINDEX, as shown above, but I would also recommend adding a COALESCE, in case your @stringtoFind it not included in your @stringhere.

    SELECT COALESCE(STUFF(@stringhere, PATINDEX('%' + @stringtofind + '%', @stringhere), LEN(@stringtofind), ' '), @stringhere)
    
    0 讨论(0)
  • 2020-11-30 14:06

    it seems you miss 2% preceding and trailing to the target string

    please try:

    select STUFF(@stringhere, PATINDEX('%' + @stringtofind + '%', @stringhere), LEN(@stringtofind), ' ')
    
    0 讨论(0)
  • 2020-11-30 14:18

    I had the same problem and made the same response as Tim Biegeleisen, but in a function:

    CREATE FUNCTION DBO.FN_REPLACE_FIRST(@X NVARCHAR(MAX), @F NVARCHAR(MAX), @R NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS BEGIN
    RETURN STUFF(@X, CHARINDEX(@F, @X), LEN(@F), @R)
    END
    

    So I just call the function instead:

    SELECT DBO.FN_REPLACE_FIRST('Text example', 'ex', 'eexx') --> Returns 'Teexxt example'
    

    The explanation is the same

    0 讨论(0)
  • 2020-11-30 14:19

    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'.

    0 讨论(0)
提交回复
热议问题