How to format a numeric column as phone number in SQL

后端 未结 10 1182
情深已故
情深已故 2020-12-05 23:26

I have table in the database with a phone number column. The numbers look like this:

123456789

I want to format that to look like this:

10条回答
  •  日久生厌
    2020-12-06 00:01

    You can also try this:

    CREATE  function [dbo].[fn_FormatPhone](@Phone varchar(30)) 
    returns varchar(30)
    As
    Begin
    declare @FormattedPhone varchar(30)
    
    set     @Phone = replace(@Phone, '.', '-') --alot of entries use periods instead of dashes
    set @FormattedPhone =
        Case
          When isNumeric(@Phone) = 1 Then
            case
              when len(@Phone) = 10 then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 4, 3)+ '-' +substring(@Phone, 7, 4)
              when len(@Phone) = 7  then substring(@Phone, 1, 3)+ '-' +substring(@Phone, 4, 4)
              else @Phone
            end
          When @phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 8, 4)
          When @phone like '[0-9][0-9][0-9] [0-9][0-9][0-9] [0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 9, 4)
          When @phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 9, 4)
          Else @Phone
        End
    return  @FormattedPhone
    

    end

    use on it select

    (SELECT [dbo].[fn_FormatPhone](f.coffphone)) as 'Phone'
    

    Output will be

提交回复
热议问题