Remove numbers from string sql server
Solution 1:
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
Solution 2:
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
Solution 3:
Try below for your query. where val is your string or column name.
CASE WHEN PATINDEX('%[a-z]%', REVERSE(val)) > 1
THEN LEFT(val, LEN(val) - PATINDEX('%[a-z]%', REVERSE(val)) + 1)
ELSE '' END
Solution 4:
One more approach using Recursive CTE..
declare @string varchar(100)
set @string ='te165st1230004616161616'
;With cte
as
(
select @string as string,0 as n
union all
select cast(replace(string,n,'') as varchar(100)),n+1
from cte
where n<9
)
select top 1 string from cte
order by n desc
**Output:**
test