I have table in the database with a phone number column. The numbers look like this:
123456789
I want to format that to look like this:
123-456-789
To format phone numbers in the US, Canada, and other NANP (North American Numbering Plan) countries, enclose the area code in parentheses followed by a nonbreaking space, and then hyphenate the three-digit exchange code with the four-digit number.
A mobile number written as +91-AAAAA BBBBB is valid throughout India, and in other countries where the + is recognized as a prefix to the country code. Since 2015, calls from mobile phones to any other mobiles do not need to prefix with a 0.
This should do it:
UPDATE TheTable SET PhoneNumber = SUBSTRING(PhoneNumber, 1, 3) + '-' + SUBSTRING(PhoneNumber, 4, 3) + '-' + SUBSTRING(PhoneNumber, 7, 4)
Incorporated Kane's suggestion, you can compute the phone number's formatting at runtime. One possible approach would be to use scalar functions for this purpose (works in SQL Server):
CREATE FUNCTION FormatPhoneNumber(@phoneNumber VARCHAR(10)) RETURNS VARCHAR(12) BEGIN RETURN SUBSTRING(@phoneNumber, 1, 3) + '-' + SUBSTRING(@phoneNumber, 4, 3) + '-' + SUBSTRING(@phoneNumber, 7, 4) END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With