How could you remove all characters that are not alphabetic from a string?
What about non-alphanumeric?
Does this have to be a custom function or are there also more generalizable solutions?
How could you remove all characters that are not alphabetic from a string?
What about non-alphanumeric?
Does this have to be a custom function or are there also more generalizable solutions?
Here's a solution that doesn't require creating a function or listing all instances of characters to replace. It uses a recursive WITH statement in combination with a PATINDEX to find unwanted chars. It will replace all unwanted chars in a column - up to 100 unique bad characters contained in any given string. (E.G. "ABC123DEF234" would contain 4 bad characters 1, 2, 3 and 4) The 100 limit is the maximum number of recursions allowed in a WITH statement, but this doesn't impose a limit on the number of rows to process, which is only limited by the memory available.
If you don't want DISTINCT results, you can remove the two options from the code.
Here's another recursive CTE solution, based on @Gerhard Weiss's answer here. You should be able to copy and paste the whole code block into SSMS and play with it there. The results include a few extra columns to help us understand what's going on. It took me a while until I understood all that's going on with both PATINDEX (RegEx) and the recursive CTE.
I just found this built into Oracle 10g if that is what you're using. I had to strip all the special characters out for a phone number compare.
Parameterized version of G Mastros' awesome answer:
Alphabetic only:
Numeric only:
Alphanumeric only:
Non-alphanumeric:
This is a very clunky way to take all of the characters that you don't want out. Problem is you have to specify which characters you don't want. If a new character comes in you it will get through unless you add it to the list.
The upside is that you don't have to create a special function. I don't have write permissions so this enables me to run from a simple query.
Using a CTE generated numbers table to examine each character, then FOR XML to concat to a string of kept values you can...