Question

Is there an easy way to replace all the text in a VARCHAR 255 column from "300-21-2" to "300-21-02" with one query? Thank you.

Was it helpful?

Solution 2

If the pattern is always the same NNN-NN-N then what you need is:

update tablex
   set column = concat( substr(column,1,7), lpad(substr(column,8),2,'0') )

see it at fiddle: http://sqlfiddle.com/#!2/f59fe/1

EDIT As the op showed the pattern

update tablex
   set column = CONCAT(  
         substring_index(col, '-',1), '-',
         lpad(substring_index(substring_index(col, '-',-2), '-', 1),2,'0'), '-',
         lpad(substring_index(col, '-',-1), 2, '0') )

If you like to convert the first set like 300 to 00300 as your pattern you add the lpad as this: lpad(substring_index(col, '-',1),5,'0')

This should be a lot easier if mysql has support to regex replace, but as it hasnt you have to work with the strings:

  • from this value: '300-02-1'
  • from substring_index(col, '-',1) I'm getting: 300
  • from substring_index(substring_index(col, '-',-2), '-', 1) I'm getting 02 I did this because just put the substring_index(col, '-',2) gave me 300-02 so, i got it from right to left (-2) then i get the first
  • and substring_index(col, '-',-1) it bring me 1 because it gets the value from right to left

Then I just concatenate it all formatting the ones I want.

OTHER TIPS

This is basic SQL

UPDATE tablename
SET columnname = '300-21-02'
WHERE columnname = '300-21-2'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top