Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Removing alpha characters and converting to numbers

$
0
0

Hello. I had a previous post where I referred to this as an Oracle SQL issue when in fact this is a Microsoft SQL question (I am working in SQL Server Mgmt Studio 2012 for this particular database...sorry for my previous confusion). I decided the best way to do this was to start over with a new question so that I can credit points properly.

One of my queries includes height and weight columns containing a variety of alpha character combinations. My goal is to convert these columns into numbers so that I can perform additional calculations. There can be thousands of rows as the data is coming from 10 hospitals (need to be able to strip any alpha character while retaining the base number at the presision presented).

Here is my small sample of of the data I cruuently have (may not include everyy possible alpha variation in these columns)

Patrick Hurst offered a nice solution (See Code Below). Perhaps I can get it to work...I am not experienced with placing functions like this in my code, but when I tried, I  noticed I am getting a syntax error when I add his code. The Error states "CREATE FUNCTION MUST BE THE ONLY STATEMENT IN THE BATCH"

CREATE FUNCTION dbo.NumberStripper (@inStr VARCHAR(100))
RETURNS @table TABLE (inString varchar(100), Numbers float, nonNumbers varchar(100))
as
BEGIN
DECLARE @str VARCHAR(100), @numbers VARCHAR(100), @nonNumbers VARCHAR(100)
SET @str = @inStr
SET @numbers = LEFT(@inStr,0)
SET @nonNumbers = LEFT(@inStr,0)
WHILE LEN(@inStr) > 0
BEGIN
 IF ISNUMERIC(LEFT(@inStr,1)) = 0
 BEGIN
  SET @nonNumbers = @nonNumbers + LEFT(@inStr,1)
 END
 ELSE
 BEGIN
  SET @numbers = @numbers + LEFT(@inStr,1)
 END
 SET @inStr = RIGHT(@inStr,LEN(@inStr)-1)
END
INSERT INTO @table 
SELECT @str, @numbers, @nonNumbers
RETURN
END
go
SELECT * 
  FROM (
        SELECT '119.9kg standg' AS txt UNION all
        SELECT '123' AS txt UNION all
        SELECT null AS txt UNION all
        SELECT '161cm'AS txt UNION ALL
		SELECT 'as123v'
       )a
    CROSS APPLY dbo.NumberStripper(a.txt)

Anyway.... appreciate any advice you can give.  Thank You.

Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>