Reformatting Phone Numbers in MSSQL

HI Experts,

I have a MSSQL table that has a varchar field for phone numbers, which are formatted as 4161234567.

I am looking to change these to the (416) 123-4567 and save them in the same field via UPDATE. So, I am wondering if within an update query I can do a SELECT and create 3 variables, then concatenate the 3 variables.

Thank you
APD TorontoSoftware DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

update your_table set phone_number =
    '(' + substring(phone_number,1,3) + ') '
    + substring(phone_number,4,3)
    + '-' + substring(phone_number,7,4)

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Jim HornMicrosoft SQL Server Data DudeCommented:
Run this in SSMS to verify that it does what you expect..
Declare @phone varchar(10) = '4161234567'
SELECT '(' + LEFT(@phone, 3) + ') ' + SUBSTRING(@phone, 4, 3) + '-' + RIGHT(@phone, 4) as phone

Open in new window

Then here's the UPDATE (rename the obvious)
UPDATE your_table
SET '(' + LEFT(phone_number, 3) + ') ' + SUBSTRING(phone_number, 4, 3) + '-' + RIGHT(phone_number, 4)

Open in new window

>and save them in the same field via UPDATE
I recommend instead of the UPDATE just leaving the column the way it is now, and just use the above functions in a SELECT to cosmetically display the data correctly.   At least that way you can do a quality check on the column in that it's a ten-digit number.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.