How to format a numeric column as phone number in SQL

后端 未结 10 1188
情深已故
情深已故 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:55

    I'd generally recommend you leave the formatting up to your front-end code and just return the data as-is from SQL. However, to do it in SQL, I'd recommend you create a user-defined function to format it. Something like this:

    CREATE FUNCTION [dbo].[fnFormatPhoneNumber](@PhoneNo VARCHAR(20))
    RETURNS VARCHAR(25)
    AS
    BEGIN
    DECLARE @Formatted VARCHAR(25)
    
    IF (LEN(@PhoneNo) <> 10)
        SET @Formatted = @PhoneNo
    ELSE
        SET @Formatted = LEFT(@PhoneNo, 3) + '-' + SUBSTRING(@PhoneNo, 4, 3) + '-' + SUBSTRING(@PhoneNo, 7, 4)
    
    RETURN @Formatted
    END
    GO
    

    Which you can then use like this:

    SELECT [dbo].[fnFormatPhoneNumber](PhoneNumber) AS PhoneNumber
    FROM SomeTable
    

    It has a safeguard in, in case the phone number stored isn't the expected number of digits long, is blank, null etc - it won't error.

    EDIT: Just clocked on you want to update your existing data. The main bit that's relevant from my answer then is that you need to protect against "dodgy"/incomplete data (i.e. what if some existing values are only 5 characters long)

提交回复
热议问题