Skip to content

Instantly share code, notes, and snippets.

@codenamejason
Created January 2, 2018 16:15
Show Gist options
  • Save codenamejason/5b5ca84fede4bbd70bdf275d41860e42 to your computer and use it in GitHub Desktop.
Save codenamejason/5b5ca84fede4bbd70bdf275d41860e42 to your computer and use it in GitHub Desktop.
Returns a formatted phone number
CREATE FUNCTION [dbo].[FormatPhoneNumber] (@UnformattedPhoneNumber varchar(50))
RETURNS varchar(12)
AS
BEGIN
DECLARE @FormattedPhoneNumber varchar(12)
SET @FormattedPhoneNumber = REPLACE(REPLACE(@UnformattedPhoneNumber,' ',''),'-','')
SET @FormattedPhoneNumber = CASE
WHEN ISNUMERIC(@FormattedPhoneNumber) = 1 AND LEN(@FormattedPhoneNumber) = 10
THEN SUBSTRING(@FormattedPhoneNumber,1,3) + '-' + SUBSTRING(@FormattedPhoneNumber,4,3) + '-' + SUBSTRING(@FormattedPhoneNumber,7,4)
WHEN ISNUMERIC(@FormattedPhoneNumber) = 1 AND LEN(@FormattedPhoneNumber) = 7
THEN SUBSTRING(@FormattedPhoneNumber,1,3) + '-' + SUBSTRING(@FormattedPhoneNumber,4,4)
ELSE NULL
END
RETURN @FormattedPhoneNumber -- Now Formatted...
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment