Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

UDF: Phone Format Expand / Collapse
Author
Message
Posted Tuesday, October 26, 2010 10:55 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Friday, October 15, 2010 11:40 AM
Points: 0, Visits: 0
Comments posted to this topic are about the item UDF: Phone Format
Post #1011261
Posted Wednesday, October 27, 2010 11:11 AM
SSC-Addicted

SSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-Addicted

Group: General Forum Members
Last Login: Sunday, September 29, 2013 1:24 AM
Points: 429, Visits: 1,721
This function as written may allow bad data to get formatted as what might appear as valid numbers. I liked the general idea but only wanted to allow 10 or 7-digit numbers (or 11-digits with a leading '1') to get thru the formatting filter. Otherwise, I have no idea if the number is valid so would prefer it return null in such a case. These conditions only apply to U.S. numbers.

CREATE FUNCTION udfFormatUSPhone
(
@phonenumber VARCHAR(20)
)
RETURNS VARCHAR(20)
AS
BEGIN

/** Remove White Space and non-Integer(s) values **/
WHILE PATINDEX('%[^0-9]%', LTRIM(RTRIM(@phonenumber))) > 0
BEGIN
SET @phonenumber = REPLACE(@phonenumber, SUBSTRING(@phonenumber, PATINDEX('%[^0-9]%', @phonenumber),1), '')
END

SET @phonenumber = LTRIM(RTRIM(@phonenumber))


/** Get the number of digits **/
DECLARE @NumChars INT
SET @NumChars = LEN(@phonenumber)


/** Check to see if this number has a leading value of '1' **/
IF @NumChars = 11 AND LEFT(@phonenumber,1) = '1'
BEGIN
SET @phonenumber = RIGHT(@phonenumber,10)
SET @NumChars = LEN(@phonenumber)
END


/** If valid number of digits proceed with formatting **/
IF @NumChars = 7 OR @NumChars = 10

BEGIN

SET @phonenumber = REVERSE(@phonenumber)

/** Format Phone Number **/
SET @phonenumber =
REVERSE(LEFT(@phonenumber,4)
+ '-'
+ SUBSTRING(@phonenumber,5,3)
+ COALESCE(' )'
+ NULLIF(SUBSTRING(@phonenumber,8,3),'') + '(', ''))
END

ELSE
SET @phonenumber = NULL


RETURN @phonenumber

END

 
Post #1011754
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse