Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip all non-alphabetic characters from string in SQL Server?

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?

like image 526
Even Mien Avatar asked Jun 17 '09 15:06

Even Mien


People also ask

How do I remove non alphabetic characters from a string?

A common solution to remove all non-alphanumeric characters from a String is with regular expressions. The idea is to use the regular expression [^A-Za-z0-9] to retain only alphanumeric characters in the string. You can also use [^\w] regular expression, which is equivalent to [^a-zA-Z_0-9] .


1 Answers

Try this function:

Create Function [dbo].[RemoveNonAlphaCharacters](@Temp VarChar(1000)) Returns VarChar(1000) AS Begin      Declare @KeepValues as varchar(50)     Set @KeepValues = '%[^a-z]%'     While PatIndex(@KeepValues, @Temp) > 0         Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')      Return @Temp End 

Call it like this:

Select dbo.RemoveNonAlphaCharacters('abc1234def5678ghi90jkl') 

Once you understand the code, you should see that it is relatively simple to change it to remove other characters, too. You could even make this dynamic enough to pass in your search pattern.

like image 93
George Mastros Avatar answered Sep 21 '22 21:09

George Mastros