Here's a way to remove all characters that don't fit an expected list of characters (tabs, unprintable included)... (retrofit to join to your table instead of my @Demo table). In your case, you seem to be at risk of more than one special character,
so you need something like this. The post from Narishma through stack overflow is a way to accomplish things, if for example you knew there was always one and only one special/unprintable character.
Declare @Demo Table (DID int identity, name varchar(99))
Insert @Demo select 'Al' UNION Select 'Bob$' Union Select '!Carl%' UNION Select '%D#<>?:"{}|\][+_)(*&^%$#@!~`_+?>a*vi()(d&*(&*#< >?:"{}|\][J+o_n)es(*&^%$#@!~`_+?><,./;:"' UNION Select ' Eddie '
;With Cleaner (DID, PassNo, Name, OName) as
(
Select DID
, 1 as PassNo
, Name
, Name as OName
From @Demo D
UNION ALL
Select DID
, Passno + 1
, Cast( Replace(C.Name, SubString(C.Name, CAB.BadPos, 1), '') as VarChar(99)) -- CAN.Name
, OName
From Cleaner C
Cross apply (Select Patindex('%[^ abcdefghijklmnopqrstuvwxyz0123456789-'']%', Name) as BadPos ) as CAB
where CAB.badpos > 0
)
, Cleaned as
(
Select Name, Oname from Cleaner
Where Patindex('%[^abcdefghijklmnopqrstuvwxyz0123456789-'' ]%', Name) = 0
)
Select D.*, Cleaned.Name as Cleaned_Name, Ltrim(Rtrim(Cleaned.Name)) as Trimmed_and_Cleaned
from @DEMO D
Inner join CLEANED on CLEANED.Oname = D.Name
Returns..
DID name Cleaned_Name Trimmed_and_Cleaned
1 Eddie Eddie Eddie
4 Al Al Al
5 Bob$ Bob Bob
3 %D#<>?:"{}|\][+_)(*&^%$#@!~`_+?>a*vi()(d&*(&*#< >?:"{}|\][J+o_n)es(*&^%$#@!~`_+?><,./;:" David Jones David Jones
2 !Carl% Carl Carl
-
Proposed as answer by
Naomi NModerator
Friday, October 26, 2012 4:04 PM
-
Marked as answer by
Iric WenModerator
Friday, November 02, 2012 9:15 AM