phone
--------------------
605-555-2862
(561)555-2700
904-555-5680
N/A
580-555-5371
2815558368
(254)555-8430
336-555-2797
3365557233
592-555-3181/4951
96615551222 Ext. 249
+44 7930 555271
REPLACE (searchString , findString , replaceWithString)
--BEGIN TRANSACTION --(in query analyzer/ssms you can highlight just "BEGIN TRANSACTION" to start the transaction.
--use replace to remove spaces
SELECT
Phone = REPLACE(phone, ' ', '') AS [Remove Space]
FROM sourceTable
WHERE
CHARINDEX(' ', phone) > 0
/*
--the results
phone Remove Space
---------------------- ---------------------
+44 7930 555271 +447930555271
96615551222 Ext. 249 96615551222Ext.249
*/
UPDATE sourceTable SET
Phone = REPLACE(phone, ' ', '')
WHERE
CHARINDEX(' ', phone) > 0
--ROLLBACK TRANSACTION
--COMMIT TRANSACTION
Remember, you will have to select just the “BEGIN TRANSACTION “, “COMMIT TRANSACTION”, or “ROLLBACK TRANSACTION” as needed. I leave them commented back, so it doesn’t auto-rollback after each run. That should remove spaces from the phone number; you can repeat those steps with variations to remove other bad data from phone. Try the following to remove some more bad data from the phone field.
SELECT
phone
, REPLACE(phone, ' ', '') AS [Remove Space]
, REPLACE(phone, '+', '') AS [Remove +]
, REPLACE(phone, 'n/a', '') AS [Remove n/a]
, REPLACE(phone, '-', '')
, REPLACE(phone, 'ext.', '')
FROM sourceTable
The following is what each of the above examples would do to the records.
phone Remove Space Remove + Remove na Remove - remove ext
-------------------- ------------------ -------------------- --------------------- --------------------- ------------------
(254)555-8430 (254)555-8430 (254)555-8430 (254)555-8430 (254)5558430 (254)555-8430
(561)555-2700 (561)555-2700 (561)555-2700 (561)555-2700 (561)5552700 (561)555-2700
+44 7930 555271 +447930555271 44 7930 555271 +44 7930 555271 +44 7930 555271 +44 7930 555271
2815558368 2815558368 2815558368 2815558368 2815558368 2815558368
336-555-2797 336-555-2797 336-555-2797 336-555-2797 3365552797 336-555-2797
3365557233 3365557233 3365557233 3365557233 3365557233 3365557233
580-555-5371 580-555-5371 580-555-5371 580-555-5371 5805555371 580-555-5371
592-555-3181/4951 592-555-3181/4951 592-555-3181/4951 592-555-3181/4951 5925553181/4951 592-555-3181/4951
605-555-2862 605-555-2862 605-555-2862 605-555-2862 6055552862 605-555-2862
904-555-5680 904-555-5680 904-555-5680 904-555-5680 9045555680 904-555-5680
96615551222 Ext. 249 96615551222Ext.249 96615551222 Ext. 249 96615551222 Ext. 249 96615551222 Ext. 249 96615551222 249
N/A N/A N/A N/A N/A
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)