|
|
Formatting should be done using your front end application. However if that option does not exist due to some reason, use the following T-SQL code to format Phone Numbers in SQL Server.
Note: The code shown below formats US Phone Numbers. I have covered three scenarios, however feel free to modify the code to add additional scenarios.
The 3 possible scenarios of a US Phone number input could be:
18052224353 will be returned as 1 (805) 222-4353
8052224353 will be returned as (805) 222-4353
2224353 will be returned as 222-4353
SELECT
phno,
CASE LEN(phno)
WHEN 11 THEN LEFT(phno,1)+
STUFF(STUFF(STUFF(phno,1,1,' ('),6,0,') '),11,0,'-')
WHEN 10 THEN
STUFF(STUFF(STUFF(phno,1,0,' ('),6,0,') '),11,0,'-')
WHEN 7 THEN
STUFF(phno,4,0,'-')
ELSE 'Invalid phno'
END as formatted_phno
FROM
(
SELECT
'18052224353' as phno union all
SELECT
'8052224353' as phno union all
SELECT
'888052224353' as phno union all
SELECT
'2224353' as phno
)
as t
The SQL Server STUFF function is used to replace certain characters with other characters, based on the position. For example STUFF(phno,1,1,'(') replaces the first character with '('. Similarly STUFF(phno,6,1,') ') inserts ') ' after position 6.
OUTPUT
Did you like this post?
|
|
|
||
|
|
|
|
|
|
|
subscribe via rss |
|
subscribe via e-mail |
|
|
print this post |
|
follow me on twitter |






comments
5 Responses to "Format Phone Numbers in SQL Server"i was searching for same solution. Can you show to write update query for this. The number in column PhoneNos nvarchar is like 5551212 and I want to format this column with your algorithm. plz help
Rafael
For updating a table, the code should be
update table
set phno=
CASE LEN(phno)WHEN 11 THEN LEFT(phno,1)+ STUFF(STUFF(STUFF(phno,1,1,' ('),6,0,') '),11,0,'-')WHEN 10 THEN STUFF(STUFF(STUFF(phno,1,0,' ('),6,0,') '),11,0,'-')WHEN 7 THEN STUFF(phno,4,0,'-')ELSE phno END
I have given phno instead of 'Invalid format' so that your original data will be there
many many thank you for giving update table code. it worked perfectly
Rafael
brilliant article on Phone number formatting. Can you also show me how to do it for India phone number
I have this 0091XXXXXXXXXX and I want to convert it to +91-XXXXXXXXXX
Here is the one that works for Indian format
select
phno,
case LEN(phno)
when 14 then '+'+STUFF(STUFF(phno,1,2,''),3,0,'-')
when 10 then phno
else 'Invalid phno'
end as formatted_phno
from
(
select
'00919443857375' as phno union all
select
'9447532568' as phno union all
select
'00919443858712' as phno union all
select
'2224353' as phno )
as t
Post a Comment