tags:

views:

28

answers:

2

I have a MySQL database table C with a field called Phone. I've already created a new field in the C table called PhoneFixed and I want to update that field with a modified version of the Phone field.

The PhoneFixed field will use the following statement to get its value:

Concat('(',Left(C.Phone,3),') ',Right(C.Phone,8)) As `PhoneFixed`

What statement do I need to automatically update the value of PhoneFixed to be equal to the result of the statement above for all rows in my table?

+1  A: 

If I understood you correctly, a simple UPDATE will work:

UPDATE C SET PhoneFixed = CONCAT('(', LEFT(Phone, 3), ') ', RIGHT(Phone, 8))

That will update the PhoneFixed using the Phone value from the same row.

Tatu Ulmanen
+1  A: 

If you just want to update a pre-existing PhoneFixed column for all rows, you'd run a query like this:

UPDATE C
SET PhoneFixed = CONCAT('(', LEFT(Phone, 3), ') ', RIGHT(Phone, 8))
Jacob
Perfect, thanks! I always forget the syntax for updating tables. I'm so used to running `Select` all the time, I rarely need to remember everything else.
Ben McCormack
Correct, but the concat is actually wrong for USA phone numbers ... you would probably want CONCAT('(', LEFT(Phone, 3), ') ', RIGHT(Phone, 7))
ithcy
well, the `Phone` field is currently stored as `XXX-XXX-XXXX`, so the `Right(Phone, 8)` takes into account the hyphen. I just need to format this correctly so I can join it to a main table in our system's database.
Ben McCormack