MSSQL: Replace non-numeric characters in a field?

I want to find and delete any non-numeric characters in a field.  Rather than typing out:

UPDATE table SET field = REPLACE(field,'/','')

For every character, is there a way to quickly do this?
jen_jen_jenAsked:
Who is Participating?
 
reb73Commented:
Zberteoc has a very valid point, but if you want to remove periods and possibly commas, then have a look at the  following link -

http://www.sqlservercentral.com/Forums/Topic470379-338-1.aspx

I've reproduced code from Jeff Moden's post below just in case you don't want the hassle of registering on that site -
/*
 SELECT TOP 11000 --equates to more than 30 years of dates
        IDENTITY(INT,1,1) AS N
   INTO dbo.Tally
   FROM Master.dbo.SysColumns sc1,
        Master.dbo.SysColumns sc2
 
--===== Add a Primary Key to maximize performance
  ALTER TABLE dbo.Tally
    ADD CONSTRAINT PK_Tally_N 
        PRIMARY KEY CLUSTERED (N) WITH FILLFACTOR = 100
 
--===== Allow the general public to use it
  GRANT SELECT ON dbo.Tally TO PUBLIC
GO
 
CREATE FUNCTION dbo.fnDigitsOnly (@pString VARCHAR(8000))
     -- Tally table can be found at http://www.sqlservercentral.com/scripts/Advanced+SQL/62486/
RETURNS VARCHAR(8000) AS
  BEGIN
        DECLARE @CleanString VARCHAR(8000)
         SELECT @CleanString = ISNULL(@CleanString,'')+SUBSTRING(@pString,N,1)
           FROM dbo.Tally WITH (NOLOCK)
          WHERE N<=LEN(@pString)
            AND SUBSTRING(@pString,N,1) LIKE ('[0-9]')    
 RETURN @CleanString
END
GO
*/
 
UPDATE <table> SET field = dbo.fn_DigitsOnly(field)

Open in new window

0
 
David ToddSenior DBACommented:
Hi,

Other than what you've suggested, I'd write a function called isdigit and simply loop through the string character at a time - if isdigit returns false then do the replace. Alternatively copy the digits to the end of a new string ...

HTH
  David

PS A CLR might be the fastest way to do this.
0
 
ZberteocCommented:
You can't do that and here is why:

12 is numeric
1.2 is numeric
1..2 is not numeric

but how can you possible tell that in 1..2 the correct number is 12 or 1.2? There is no way do do that with code. Only a human can decide what value is correct in a situation like this.!

You need to identify all the non-numeric values for that column ad deal with them manually.

That's why a correct design and ahead planing is of such importance.

To identify the non-umeric values:


SELECT 
	col
from 
	YourTable
where
	isnumeric(col)<>1

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.