Home Forums SQL Server 2008 SQL Server 2008 - General Using REPLACE with a string where I need to replace %anystring% with some new string RE: Using REPLACE with a string where I need to replace %anystring% with some new string

  • Alternatively, if you really need to use Replace instead of Stuff for this, try using Substring to get the piece that you want to replace. Build the Substring parameters the same way I did the Stuff position and length. Then use that as the first argument for the Replace function.

    SELECT string,

    SUBSTRING(string, CHARINDEX('%', string, 1),

    CHARINDEX('%', string, CHARINDEX('%', string, 1) + 1) - CHARINDEX('%', string, 1) + 1),

    REPLACE(string,

    SUBSTRING(string, CHARINDEX('%', string, 1),

    CHARINDEX('%', string, CHARINDEX('%', string, 1) + 1) - CHARINDEX('%', string, 1) + 1),

    'replaced')

    FROM (SELECT 'somestring+%sometext%' AS string

    UNION ALL

    SELECT '%sometext%'

    UNION ALL

    SELECT 'somestring+%sometext%+somesecondstring') AS Example;

    Either will work. Just thought of the nested Replace(Substring()) version second is all.

    - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
    Property of The Thread

    "Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon