SELECT CASE LEN(phone) WHEN 11 THEN LEFT(phone, 1) + STUFF(STUFF(STUFF(phone, 1, 1, ' ('), 6, 0, ') '), 11, 0, '-') WHEN 10 THEN STUFF(STUFF(STUFF(phone, 1, 0, ' ('), 6, 0, ') '), 11, 0, '-') WHEN 7 THEN STUFF(phone, 4, 0, '-') ELSE 'Invalid phone' END AS 'Formatted Phone' FROM TABLE
If you have to sanitize your field first it gets ugly but is still possible
CASE LEN(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone, '.', ''), '-', ''), '(', ''), ')', ''), ' ', '')) WHEN 11 THEN LEFT(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone, '.', ''), '-', ''), '(', ''), ')', ''), ' ', ''), 1) + STUFF(STUFF(STUFF(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone, '.', ''), '-', ''), '(', ''), ')', ''), ' ', ''), 1, 1, ' ('), 6, 0, ') '), 11, 0, '-') WHEN 10 THEN STUFF(STUFF(STUFF(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone, '.', ''), '-', ''), '(', ''), ')', ''), ' ', ''), 1, 0, ' ('), 6, 0, ') '), 11, 0, '-') WHEN 7 THEN STUFF(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone, '.', ''), '-', ''), '(', ''), ')', ''), ' ', ''), 4, 0, '-') ELSE 'Invalid phone' END AS Phone
Reference: http://www.sqlservercurry.com/2010/11/format-phone-numbers-in-sql-server.html
Last Updated on October 26, 2015