fnPhoneFix function created to fix all common phone numbers errors to and normalizes phone numbers.
Function removes all Non-Numeric characters, reduces above 10 digit numbers to 10, below 10 numbers set to '' and all repeating numbers like 2222222222 set to ''. These are the most common errors needing to fix a phone number improperly screened.
To Create the fnPhoneFix Function use the following code:
CREATE FUNCTION [dbo].[fnPhoneFix](@PhoneOld VarChar(20))
Returns VarChar(10)
AS
Begin
Declare @iCnt Int = 0
Declare @PhoneNew VarChar(15) = ''
IF @PhoneOld IS NULL
RETURN NULL;
While @iCnt <= LEN(@PhoneOld)
Begin
IF Substring(@PhoneOld,@iCnt,1) >= '0' AND Substring(@PhoneOld,@iCnt,1) <= '9'
Begin
SET @PhoneNew = @PhoneNew + Substring(@PhoneOld,@iCnt,1)
End
Set @iCnt = @iCnt + 1
End
If LEN(@PhoneNew) > 10 and Left(@PhoneNew, 1) = '1'
Set @PhoneNew = RIGHT(@PhoneNew,10);
Else
Set @PhoneNew = Left(@PhoneNew,10);
If @PhoneNew = '0000000000' or @PhoneNew = '1111111111'
or @PhoneNew = '2222222222' or @PhoneNew = '3333333333' or @PhoneNew = '4444444444'
or @PhoneNew = '5555555555' or @PhoneNew = '6666666666' or @PhoneNew = '7777777777'
or @PhoneNew = '8888888888' or @PhoneNew = '9999999999' or LEN(@PhoneNew) <> 10
Set @PhoneNew ='';
Return @PhoneNew
End
You can add formatting of @PhoneNew if you want to set numbers to a standardized Phone Format or leave as just as 10 digit numbers.
If @PhoneNew = ''
Return Null;
Else
Return (Left(@PhoneNew, 3) + '-' + Substring(@PhoneNew,4,3) + '-' + Right(@PhoneNew, 4));
A sample query to Update all phone numbers in a Table by using the Function. Can also be used to update a single record, but most often used to clean up a table. Then delete all Null or '' records in table and then doing a simple count query would give you a count of good phone numbers.
Print'/*Fix Phone Numbers Call*/'
Update tblTemp
Set Phone = dbo.fnPhoneFix(tblTemp.Phone)
From tblTemp