Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove numbers from string sql server

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.

like image 758
CR41G14 Avatar asked Nov 05 '12 21:11

CR41G14


People also ask

How do you trim a number in a string in SQL?

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.

How do I select only numeric values in SQL?

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.


2 Answers

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

like image 177
Jatin Avatar answered Sep 21 '22 15:09

Jatin


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 
like image 43
Ben Anderson Avatar answered Sep 21 '22 15:09

Ben Anderson