Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a numeric column as phone number in SQL

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 
like image 585
avnic Avatar asked Sep 15 '09 11:09

avnic


People also ask

What is numeric format for phone number?

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.

How do you enter a mobile number in numeric format?

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.


1 Answers

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 
like image 61
David Andres Avatar answered Sep 20 '22 14:09

David Andres