user1298426 user1298426 - 1 year ago 69
SQL Question

Use replace() function in an update to change more than one sub string of a column

Say I have

table with a column

column has values 'studentone', 'studenttwo', 'studentthree'

& I want to replace them with 'student1', 'student2', 'student3'.

For single replacement it's quite straight forward:

update student set name = replace(name, 'one', '1')

But what about multiple replacements? Any idea?

Answer Source

I would just use multiple update statements, but if you absolutely must do it in one statement, just nest the replace calls:

update student set
  name = replace(replace(replace(name, 'one', '1'), 'two', '2'), 'three', '3')

This works because (although inefficient) calls to replace() have no effect if the search term is not found.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download