ddf_Phone

In our SQL library we keep quite a few functions that get moved from project to project.

Today's example is the ddf_phone function. This function takes a phone number in the format of '12345678901234' and formats it to '(123) 456-7890 x1234'

That's the standard format in Dynamics GP

 

 

IF EXISTS (SELECT *
       FROM   sysobjects
       WHERE  name = N'ddf_phone')
    DROP FUNCTION ddf_phone
GO
 
 
CREATE FUNCTION ddf_phone
    (@phone  varchar(21))
 
Returns varchar(30)
 
AS
begin
    declare @out varchar(200)
    set @out = ''
    declare @phone2 varchar(20)
    set @phone2 = ''
    declare @pos as int
    set @pos = 0
         
    --remove any special chars
    while @pos < len(@phone) begin
        set @pos = @pos + 1    
     
        if isnumeric(substring(@phone,@pos,1)) > 0 and substring(@phone,@pos,1) <> '-' begin
            set @phone2 = @phone2 + substring(@phone,@pos,1)
        end
         
    end
 
    if @phone is null or @phone = '' begin
        return('')
    end
     
    if len(@phone2) >= 10 begin
        set @out = '('
        set @out = @out + substring(@phone2,1,3)
        set @out = @out + ') '
        set @out = @out + substring(@phone2,4,3)
        set @out = @out + '-'
        set @out = @out + substring(@phone2,7,4)
        if substring(@phone2,11,99) > '' begin
            set @out = @out + ' ' + substring(@phone2,11,99)
        end
     
        return (@out)
    end
     
    if len(@phone2) = 7 begin
        set @out = @out + substring(@phone2,1,3)
        set @out = @out + '-'
        set @out = @out + substring(@phone2,4,4)
     
        return (@out)
    end
     
    set @out = @phone2
    return (@out)
end
 
go
 
grant all on ddf_phone to public

RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences