MSSQL Format U.S. Phone Number

|
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

Originally Posted on October 13, 2014
Last Updated on October 26, 2015
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.