Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come formattare una colonna numerica come numero di telefono in SQL

Questo dovrebbe farlo:

UPDATE TheTable
SET PhoneNumber = SUBSTRING(PhoneNumber, 1, 3) + '-' + 
                  SUBSTRING(PhoneNumber, 4, 3) + '-' + 
                  SUBSTRING(PhoneNumber, 7, 4)

Incorporato il suggerimento di Kane, puoi calcolare la formattazione del numero di telefono in fase di esecuzione. Un possibile approccio sarebbe utilizzare le funzioni scalari per questo scopo (funziona in SQL Server):

CREATE FUNCTION FormatPhoneNumber(@phoneNumber VARCHAR(10))
RETURNS VARCHAR(12)
BEGIN
    RETURN SUBSTRING(@phoneNumber, 1, 3) + '-' + 
           SUBSTRING(@phoneNumber, 4, 3) + '-' + 
           SUBSTRING(@phoneNumber, 7, 4)
END