SQL: converting a column of numeric and null values to FLOAT - sql

I have a table with a column of varchar type. The column contains 568710 records of numeric (I mean the ISNUMERIC() returns 1) and 91 records of null values (i.e., the ISNUMERIC() returns 0). Now, I need to convert the column to FLOAT without losing the null records or replacing them with any other value. Is it possible in SQL?
When I use CONVERT(FLOAT, [Value]) conversion, I get the following error:
Msg 8114, Level 16, State 5, Line 48
Error converting data type varchar to float.
I read that the null can be converted to any type. So it should be possible.

You can use this
SELECT CONVERT(float, CASE WHEN ISNUMERIC(columnName) = 1 THEN columnName ELSE NULL END) FROM TableABC

Try :::
ALTER TABLE tablename
ADD NewFloatColumn FLOAT
UPDATE TableName
SET NewFloatColumn =
CASE WHEN ISNUMERIC(VarcharColumn) =1 THEN CAST (VarcharColumn AS float)
WHEN UPPER(VarcharColumn) = 'NULL' THEN null
END

Select (CASE WHEN ISNUMERIC(c) = 1
THEN (CASE WHEN c LIKE '%.%' THEN c ELSE c + '.00' END)
ELSE '0.00'
END)from table_name

I just spent some time scratching my head at the same problem. I was able to resolve this by converting first to int, then to float. Testing shows no data loss as my float column did not contain decimal, it simply had to match the dtype of another column for a later UNION operation.
This was completed on SQL Server 2016.
ALTER TABLE table1
ALTER COLUMN column1 int;
ALTER TABLE table1
ALTER COLUMN column1 float;

Related

SQL Round if numerical?

(Beginner at sql)
I've been getting the error
'Error converting data type nvarchar to float.'
Which is because I was trying to round an nvarchar(10) column with both characters and integers, and obviously it can't round the characters. (I can't make two separate columns with different data types as they both need to be in this column)
I'm looking for a way to round the numbers in the nvarchar column whilst also returning the characters
I've being trying CAST/Converts nothing seems to work
I've also tried
CASE WHEN ISNUMERIC(Tbl1.Column1) = 1
THEN cast(Round(Tbl1.Column1, 0) AS float)
ELSE Tbl1.Column1 END AS 'Column1'
in the select statement
I cant figure out what else will solve this!
Sample Data in this column would be
8.1
2
9.0
9.6
A
-
5.3
D
E
5.1
-
I would go for try_convert() instead of isnumeric():
COALESCE(CONVERT(VARCHAR(255), TRY_CONVERT(DECIMAL(10, 0), Tbl1.Column1)),Tbl1.Column1) as Column1
A conversion problem arises with your approach because a case expression returns a single value. One of the branches is numeric, so the return type is numeric -- and the conversion in the else fails.
You can fix your version by converting the then clause to a string after converting to a float.
since you hold both types in this column, you need to cast your rounded value back to varchar
declare #Tbl1 table (Column1 varchar(10))
insert into #Tbl1 (Column1) values ('8.1'), ('2'), ('9.0'),
('9.6'), ('A'), ('5.3'),
('D'), ('E'), ('5.1'), ('-')
select case when TRY_CONVERT(float, Column1) IS NULL then Column1
else cast(cast(Round(Column1, 0) as float) as varchar(10))
end AS 'Column1'
from #Tbl1
outcome is
Column1
-------
8
2
9
10
A
5
D
E
5
-
In case you get the error TRY_CONVERTis not a build-in function then you have your database compatibility level is less that SQL 2012.
You can correct that using this command
ALTER DATABASE your_database SET COMPATIBILITY_LEVEL = 120;
Also note that after this statement the answer of Gordon is working now, and I agree that is a better answer then mine

SQL Server - Convert String to float with N/A's present

I have a flat file that I loaded into SQL Server using the import wizard. All columns are stored as nchar(50).
I'm now trying to convert the table to a new table with various types (char, float, int, etc).
There is one column that I'd like to convert to float but it contains N/A strings.
I checked that there weren't any other weird string using this:
SELECT col1, count(*)
from tab1
where ISNUMERIC(col1) <> 1
group by col1
Then I wrote a CASE statement to do the conversion:
SELECT CASE WHEN col1 = 'N/A' THEN NULL ELSE CAST(col1 AS FLOAT) END col1
INTO tab2
FROM tab1
But I'm getting this error message:
Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to float.
Any idea what's causing this?
If 2012+ Use try_convert()
SELECT col1, count(*)
from tab1
where try_convert(float,col1) is null
group by col1
You can use try_convert if you want to ignore invalid chars to float as below
Select try_convert(float, col1) as col1 from yourtable
Careful on using ISNUMERIC() for this. It can return some false positives. For example...
select isnumeric('$')
select isnumeric('1e4')
This should show you what is causing the error.
select * from table where column like '%[^0-9\.]%' escape '\'
You can use this in a where clause, or use TRY_CONVERT()
You aren't doing the type conversion from the String to the float. In your SQL statements you need to explicitly cast the original column type from nvarchar to float. Something like this might work:
SELECT
CASE
WHEN col1 = 'N/A' THEN NULL
ELSE CAST(col1 AS FLOAT)
END col1
INTO tab2
FROM tab1

SQL : Error converting data type nvarchar to float

I want to convert nvarchar data to float type.
In my case I have SalesValue column and I used this command
UPDATE Overseas
SET SalesValue = CONVERT(FLOAT, REPLACE([SalesValue],',','') )
My table has values like
201.01
40.50
215.12
550
304.201
But I get an error
SQL : Error converting data type nvarchar to float.
How can I solve this problem ?
You should find the values that do not match. In SQL Server 2012+, you can use try_convert(). That is not available. So, how about this?
SELECT SalesValue
FROM Overseas
WHERE SalesValue LIKE '%[^0-9,.]%' OR
SalesValue LIKE '%[.,]%[.,]%';
I think that covers the obvious irregularities: a character that is not numeric or two (or more) decimal points.
1st cast value by using below query and then update normally
SELECT
case when ISNUMERIC([SalesValue])=1
then CAST([SalesValue] AS FLOAT) else 0 end AS CastedValue)
FROM your_table_name
It sounds like to me your data still has something that is non numerical. I'm hoping that your application side had done a pretty good job at cleaning your data before inputting and the problem is probably you have a '$' in one or more of your fields.
Cast will fail when you have a non numerical char other then '.' in it (as you probably know which is why you removed ',').
I ran the below script to test this.
declare #myFloat float;
declare #test1 nvarchar(10) = '145.88';
declare #test2 nvarchar(10) = '4,145.88';
declare #test3 nvarchar(10) = '$4,145.88';
SELECT ISNUMERIC(#TEST3)
set #myFloat = CONVERT(FLOAT, REPLACE(#test1,',','') );
select #myFloat;
set #myFloat = CONVERT(FLOAT, REPLACE(#test2,',','') );
select #myFloat;
--THIS WILL FAIL
set #myFloat = CONVERT(FLOAT, REPLACE(#test3,',','') );
select #myFloat;
--THIS WILL NOT FAIL
set #myFloat = CONVERT(FLOAT, REPLACE(REPLACE(#test3,',',''),'$','') );
select #myFloat;
You can try running the below script on the column in question to see which columns you are having a problem with:
--run this on your table
SELECT SalesValue
FROM Overseas
WHERE ISNUMERIC(REPLACE(SalesValue,',','')) = 0
--test sample
/*
insert into #myTable
values ('145.88'),
('4,145.88'),
('$4,145.88'),
('$4,145.88%');
SELECT *
FROM #myTable
WHERE ISNUMERIC(REPLACE(amounts,',','')) = 0
--WHERE ISNUMERIC(REPLACE(REPLACE(amounts,',',''),'$','')) = 0 --this will remove results with $ also
*/
So your fix will be to simply change the line you provided to:
UPDATE Overseas SET SalesValue = CONVERT(FLOAT, REPLACE(REPLACE([SalesValue],',',''),'$','') )
Unless you found other chars in the results of prior script.
This will get you closer than ISNUMERIC()
declare #table table (SalesValue varchar(16))
insert into #table
values
('1e4'),
('$'),
('134.55'),
('66,9897'),
('14')
select
SalesValue
,case
when SalesValue NOT LIKE '%[^0-9,.]%'
then convert(decimal(16,4),replace(SalesValue,',','.'))
end
from
#table

Data type varchar to numeric

I have a table with Varchar values that are numbers, and I want them to be decimal values. I'm getting an error saying Error converting data type varchar to numeric. I've tried:
SELECT ROUND(CAST(MYCOLUMN AS decimal(10, 2)), 2)
FROM TABLE
and
ALTER TABLE MYTABLE
ALTER COLUMN MYCOLUMN DECIMAL(10,2)
and
ALTER TABLE MYTABLE
MODIFY COLUMN ACQ_FIELD_8 DECIMAL(10,2)
and
SELECT ISNULL(CAST(NULLIF(MYCOLUMN, 'NULL') AS NUMERIC(10,2)), 0)
FROM MYTABLE
and I keep getting the same error. I looked the through the data to look for any special characters or letters by using:
SELECT MYCOLUMN FROM MYTABLE
WHERE MYCOLUMN LIKE '%[a-zA-Z]%'
or MYCOLUMN LIKE '%[(]%' --etc for each character.
The only thing that I have found is that every value for some reason has a '^' in it, but when I replace the '6' with nothing, the value still can't be converted to a decimal or numeric. If I try ordering the column by number (< 0.00), I get Arithmetic overflow error converting varchar to data type numeric.
Anyone know what to do?
Try this :
select round(try_convert(decimal(10,2), Mycolumn),2)
looks like you have some values which can not be converted to decimal. try_convert will convert them as NULL
You can try isnumeric:
SELECT ROUND(CAST(MYCOLUMN AS decimal(10, 2)), 2)
FROM TABLE
WHERE isnumeric(MYCOLUMN) = 1

Error when converting varchar(max) to int or float

I have a table that stores different info into a value column as varchar(max)
I need to be able to extract some of the info from this table, convert it to an integer and average the numbers. I'm running into an issue though when trying to convert.
This does not work:
select cast(value as float) as value
from table
Can anyone tell me how to properly convert this?
Presumably, the problem is that some values are not in a numeric format. Try this instead:
select (case when isnumeric(value) = 1 then cast(value as float) end)
from table
This converts all the numbers to float, and puts NULLs in the remaining fields.
If you want to see the values that are causing problems, use this:
select value
from table
where isnumeric(value) = 0 and value is not null