Replace first occurrence of substring in a string in SQL

后端 未结 4 866
粉色の甜心
粉色の甜心 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: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

提交回复
热议问题