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

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

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

MSSQL Server 2008 - Convert Nvarchar to numeric

im using mssql 2008 and Im permanently failing to convert an nvarchar to numeric values.
Can you please advise? I have different solutions I found over the www, but all of them are failing with the error message:
Msg 8114, Level 16, State 5, Line 15 Error converting data type
nvarchar to numeric.
I have built an reduced example for demonstration purpose:
IF OBJECT_ID('tempdb..#temptable', 'U') IS NOT NULL
DROP TABLE dbo.#temptable
create table #temptable(
col1 nvarchar(10),
col2 numeric(10,5)
)
insert into #temptable values ('0,5','0')
select *,convert(numeric(18,2),col1) from #temptable
UPDATE #temptable
SET col2 = CAST(col1 AS numeric(10,5))
WHERE ISNUMERIC(col1) = 1
SELECT col1
, CASE ISNUMERIC(col1)
WHEN 1 THEN CONVERT(numeric(18,2),col1)
ELSE 0.00
END
from #temptable
I alreay found an strong hint whats going wrong... the issue seems to be related to the , as seperator while the SQL server expects an .
if you change the following line to:
insert into #temptable values ('0.5','0')
its working
The problem is you are using ISNUMERIC(col1) = 1 which fails for a ton of cases like ISNUMERIC('1e4') or ISNUMERIC('$') or in your case, ISNUMERIC('1,000,000'). Don't use ISNUMERIC in this fashion.
Instead, try this...
UPDATE #temptable
SET col2 = CAST(col1 AS numeric(10,5))
WHERE col1 not like '%[^0-9.]%'
Use try_convert() in SQL Server 2012+:
UPDATE #temptable
SET col2 = TRY_CONVERT(numeric(10,5), col1)
WHERE ISNUMERIC(col1) = 1;
SQL Server re-arranges expression valuation in a query. So, the CAST() might be implemented before the WHERE -- resulting in the error. You can make a similar change to the SELECT version of your query.
In SQL Server 2008, you should be able to do effectively the same thing using CASE:
UPDATE #temptable
SET col2 = (CASE WHEN ISNUMERIC(col1) = 1 THEN CONVERT(numeric(10, 5), col1) END)
WHERE ISNUMERIC(col1) = 1;
Note: There may be cases where ISNUMERIC() returns "1", but the value cannot be converted (for instance, overflow). In that case, this version would still fail.

Show 'Unknown' for Null Ids in SQL

when the numeric field is Null how to show a string value? Tried the syntax below but getting an error
'Error converting data type varchar to numeric':
Syntax:
select
case
when bill_area_id IS null then 'Unknown'
else bill_area_id end from Table_name
Use coalesce to return first non-null value :
select coalesce(bill_area_id, 'Unknown') from Table_name
Note that compatible data types is required. I.e. you may have to do :
select coalesce(cast(bill_area_id as varchar(15)), 'Unknown') from Table_name
If you are using sql server, you can also use this :
select isnull(cast(bill_area_id as varchar(15)), 'Unknown') from Table_name
The error is because you are mixing varchar with numeric output in the same column. For SQL Server for example:
select
case
when bill_area_id IS null then 'Unknown'
else CAST(bill_area_id as varchar) end from Table_name
Ensures that the output is uniformly varchar since I am casting bill_area_id as varchar, or selecting 'Unknown' (also a varchar).
There are other answers here using COALESCE/isnull that are just as valid, since those functions provide an alternative to NULL values.

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

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;

SQL Server : Nvarchar to Varchar

I have a table with two columns, one is of type Varchar and the other in NVarchar.
I want to update all the rows so VarcharField = NVarcharField.
It won't let me because some of the rows contain chars that are not allowed in varchar column with the current code page.
How can I find these rows?
Is it possible to remove any char that doesn't fit the specific code page I'm using?
SQL Server 2012.
You can find the rows by attempting to convert the nvarchar() col to varchar():
select nvarcharcol
from t
where try_convert(varchar(max), nvarcharcol) is null;
Try this..
to find the rows with values that are not supported by varchar
declare #strText nvarchar(max)
set #strText = 'Keep calm and say தமிழன்டா'
select cast(#strText as varchar(max)) col1 , N'Keep calm and say தமிழன்டா' col2
Here #strText has non-english chars, When you try to cast that into varchar the non-english chars turns into ????. So the col1 and col2 are not equal.
select nvar_col
from tabl_name
where nvar_col != cast(nvar_col as varchar(max))
Is it possible to remove any char that doesn't fit the specific code page I'm using?
update tabl_name
set nvar_col = replace(cast(nvar_col as varchar(max)),'?','')
where nvar_col != cast(nvar_col as varchar(max))
Replace ? with empty string and update them.
If Gordon's approach doesn't work because you get question marks from TRY_CONVERT instead of the expected NULL, try this approach:
SELECT IsConvertible = CASE WHEN NULLIF(REPLACE(TRY_CONVERT(varchar(max), N'人物'), '?',''), '') IS NULL
THEN 'No' ELSE 'Yes' END
If you need it as filter for the rows that can't be converted:
SELECT t.*
FROM dbo.TableName t
WHERE NULLIF(REPLACE(TRY_CONVERT(varchar(max), t.NVarcharField), '?',''), '') IS NULL