-1

I have a value in a database column VALUE:

C_4327

I need to strip the non numeric text from this so that it just leaves the numbers. I have tried using the REPLACE function within SQL but not I don't want to replace, just strip them out. I was previously using PHP to do this:

preg_replace("/[^0-9]/","",$row['VALUE']);

I'm retrieving the value in a SELECT statement.

Your help would be appreciated.

Thanks in advance

6
  • you want to trim it and save again in DB or ? Commented Jan 28, 2014 at 15:55
  • I would like to display the answer in my while loop below. So returning $valueID = $row['VALUE']; or similar if I did a REPLACE(...) AS companyID.. Is what I'm after but of course only displaying the numbers, not the other characters. Commented Jan 28, 2014 at 16:01
  • The replace function as part of a select statement will not change any data in the database. Commented Jan 28, 2014 at 16:02
  • Means that regex didn't work at all, then Commented Jan 28, 2014 at 16:02
  • I don't want to change anything in the database, I just want to strip it on the page. Commented Jan 28, 2014 at 16:05

3 Answers 3

2

If you want to get the number at the end of the string, you can use the following arcane approach:

select reverse(reverse(value) + 0) as NumberAtEnd;

In your case:

  • value ='C_4327'
  • reverse(value) = '7234_C'
  • reverse(value) + 0 = 7234
  • reverse(reverse(value) + 0) = '4327'
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is exactly what I was looking for and it has worked. Thanks again.
1

you can create a Function like that/.

  CREATE FUNCTION GetNumeric
 (
 @strAlphaNumeric VARCHAR(256))
 RETURNS VARCHAR(256)
 AS BEGIN
 DECLARE @intAlpha INT
 SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
 BEGIN
 WHILE
 @intAlpha > 0
 BEGIN
 SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
 SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
 END
 END
 RETURN ISNULL(@strAlphaNumeric,0)
 END
 GO

then call the function as follows

   SELECT GetNumeric('123456789blahblahblah') AS filedname FROM your_table

you will get the answer : 123456789

Comments

0

simple way: how about substring...

select substr( value, 3 ) from mytable;

it works on your example - but not sure if your real data is more complicated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.