C# / .NETDevOpsMisc
Misc
MSSQL Standardize Phone Numbers
Alexandru Puiu
Alexandru Puiu
July 15, 2022
1 min

MSSQL Standardize Phone Numbers

Recently I had to clean up a database of wildly varying phone number formats. Hopefully, it saves someone else some time.

# Replace spaces with dashes to eliminate the simple stuff first for speed
update orders set phone=REPLACE(Phone, ' ', '-') where phone not like '[0-9]{3}-[0-9]{3}-[0-9]{4}'

# Insert the 2nd missing dash
update orders set phone=STUFF(Phone, 7, 0, '-') where phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9]'

# Remove all formatting characters, parse the number as a bigint and if parsing is successful, format
update orders set Phone=FORMAT(TRY_CAST(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Phone, '`', ''), '/', ''), '_', ''), '''', ''), ' ', ''), '.', ''), ')', ''), '(', ''), '-', '') AS bigint), '000-000-0000') from orders where phone not like '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' and Phone is not null and TRY_CAST(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Phone, '`', ''), '/', ''), '_', ''), '''', ''), ' ', ''), '.', ''), ')', ''), '(', ''), '-', '') AS bigint) is not null

# Remove the country code digit
update orders set Phone=SUBSTRING(phone, 2, 8000) from orders where phone like '[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]'

Tags

mssqlutils
Alexandru Puiu

Alexandru Puiu

Engineer / Security Architect

Systems Engineering advocate, Software Engineer, Security Architect / Researcher, SQL/NoSQL DBA, and Certified Scrum Master with a passion for Distributed Systems, AI and IoT..

Expertise

.NET
RavenDB
Kubernetes

Social Media

githubtwitterwebsite

Related Posts

RavenDB Integration Testing
C# / .NET
Using RavenDB in Integration Testing
December 24, 2022
2 min

Subscribe To My Newsletter

I'll only send worthwhile content I think you'll want, less than once a month, and promise to never spam or sell your information!
© 2023, All Rights Reserved.

Quick Links

Get In TouchAbout Me

Social Media