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

  • GSquared (8/13/2012)


    I could be wrong, but I'm pretty sure Replace() won't take regex or other patterns. I'm pretty sure it only deals with strings or string-type variables with pre-defined values.

    However, solving this with Stuff() would be quite easy.

    SELECT string,

    CHARINDEX('%', string, 1),

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

    STUFF(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;

    The first three columns are just the internal pieces of the logic. The final column is what you need for this kind of thing.

    Interesting... Thanks G. I think you are right that REPLACE() does not accept patterns. That's why my RegEx wasn't working 🙂

    Jared
    CE - Microsoft