How to format a numeric column as phone number in SQL

后端 未结 10 1189
情深已故
情深已故 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-05 23:56

    Above users mentioned, those solutions are very basic and they won't work if the database has different phone formats like:

    (123)123-4564
    123-456-4564
    1234567989
    etc
    

    Here is a more complex solution that will work with ANY input given:

    CREATE FUNCTION [dbo].[ufn_FormatPhone] (@PhoneNumber VARCHAR(32))
    RETURNS VARCHAR(32)
    AS
    BEGIN
        DECLARE @Phone CHAR(32)
    
        SET @Phone = @PhoneNumber
    
        -- cleanse phone number string
        WHILE PATINDEX('%[^0-9]%', @PhoneNumber) > 0
            SET @PhoneNumber = REPLACE(@PhoneNumber, SUBSTRING(@PhoneNumber, PATINDEX('%[^0-9]%', @PhoneNumber), 1), '')
    
        -- skip foreign phones
        IF (
                SUBSTRING(@PhoneNumber, 1, 1) = '1'
                OR SUBSTRING(@PhoneNumber, 1, 1) = '+'
                OR SUBSTRING(@PhoneNumber, 1, 1) = '0'
                )
            AND LEN(@PhoneNumber) > 11
            RETURN @Phone
    
        -- build US standard phone number
        SET @Phone = @PhoneNumber
        SET @PhoneNumber = '(' + SUBSTRING(@PhoneNumber, 1, 3) + ') ' + SUBSTRING(@PhoneNumber, 4, 3) + '-' + SUBSTRING(@PhoneNumber, 7, 4)
    
        IF LEN(@Phone) - 10 > 1
            SET @PhoneNumber = @PhoneNumber + ' X' + SUBSTRING(@Phone, 11, LEN(@Phone) - 10)
    
        RETURN @PhoneNumber
    END
    

提交回复
热议问题