SQLTeam.com | Weblogs | Forums

Select Replace with multiple replacements


I have a table of names, that have been converted to upper/lower case but suffixes like II, III, and IV got converted to Ii, Iii and Iv.
So for example,

select REPLACE(name,' iv',' IV') from Person where name like '% iv'
fixes the one with suffix "IV"

But how do I fix all 3 in one Select statement?

SELECT  Replace(Replace(Replace(NameField, ' iv', ' IV'), ' ii', ' II'), ' iii', ' III') CorrectedName
FROM TableName
Where Right(NameField, 3) IN (' ii', 'iv') or Right(NameField, 4) = ' iii');


When I have nested REPLACE like this I write then thus:

    , ' iv', ' IV')
    , ' ii', ' II')
    , ' iii', ' III')

as I think that makes it easier to "add more", or rearrange the order (if that turns out to be important) over time.

Note that those REPLACEs will ALSO change "Ivan" to "IVan", and so on. You might be able to improve on that by adding a prefix space, but there is still a risk that matches something within the NameField

    , '  iv', '  IV')
    , '  ii', '  II')
    , '  iii', '  III')

if the suffixes are always at the end of the string? then you could probably further "ring-fence" the replacements like this:

    NameField+'~' --- where "~" is a character which does NOT occur anywhere in the NameField
    , '  iv~', '  IV~')
    , '  ii~', '  II~')
    , '  iii~', '  III~')
    , '~', '')


thank you.


Thank you.


I changed the last line, in my earlier post, to Ahem!! ... "Fix a bug" :slight_smile: