I have a large database in which I want to do a part string search. The user will enter characters: JoeBloggs.
For arguments sake if I had a name Joe 23 Blo Ggs 4
in the database. I want to remove everything in the name other than A-Z.
I have the REPLACE(Name, ' ','')
function to remove spaces and the UPPER()
function to capitalize the name.
Is there a more efficient fast way maybe by terms of regex to replace anything other than A-Z. I cannot change the values in the database.
SQL Server TRIM() FunctionThe TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string. Note: Also look at the LTRIM() and RTRIM() functions.
SQL Server ISNUMERIC() Function The ISNUMERIC() function tests whether an expression is numeric. This function returns 1 if the expression is numeric, otherwise it returns 0.
1st option -
You can nest REPLACE()
functions up to 32 levels deep. It runs fast.
REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (@str, '0', ''), '1', ''), '2', ''), '3', ''), '4', ''), '5', ''), '6', ''), '7', ''), '8', ''), '9', '')
2nd option -- do the reverse of -
Removing nonnumerical data out of a number + SQL
3rd option - if you want to use regex
then http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=27205
This one works for me
CREATE Function [dbo].[RemoveNumericCharacters](@Temp VarChar(1000)) Returns VarChar(1000) AS Begin Declare @NumRange as varchar(50) = '%[0-9]%' While PatIndex(@NumRange, @Temp) > 0 Set @Temp = Stuff(@Temp, PatIndex(@NumRange, @Temp), 1, '') Return @Temp End
and you can use it like so
SELECT dbo.[RemoveNumericCharacters](Name) FROM TARGET_TABLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With