June 27, 2010

Remove and Replace Special Characters in a SQL Server Column




Here’s a sample output of a SQL Server Column containing special characters, obtained from different sources.

image

As you can observe, the format of the numbers is not uniform. What is needed is a uniform format like 111-111-1111

Here’s how to remove and replace these special characters using REPLACE to obtain the desired output:

-- SAMPLE DATA
DECLARE @TT TABLE (Phone varchar(15))
INSERT INTO @TT VALUES
('(100)-111-2222'),
(
'(101)111-2222'),
(
'111-111-2222'),
(
'(110)-100-2222'),
(
'(111)111-2222'),
(
'112-111-2222'),
(
'(121)111-2222')

-- QUERY
SELECT
REPLACE(
REPLACE(
REPLACE(
Phone,
'(', '' ),
')-', '-' ),
')', '-' ) as Phone
FROM @TT

OUTPUT

image

Note: This approach works well when the number of characters to be replaced are few.


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

1 Response to "Remove and Replace Special Characters in a SQL Server Column"
  1. Madhivanan said...
    July 1, 2010 at 11:35 PM

    If number of characters to be removed is more in number, you can use either of these

    http://beyondrelational.com/blogs/madhivanan/archive/2010/01/08/replace-data-of-one-table-with-data-of-other-table.aspx

    http://beyondrelational.com/blogs/madhivanan/archive/2009/05/11/removing-unwanted-characters.aspx

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions