SQL converting float to varchar - sql

I've 2 columns which I want to use a condition on. But I get this error message and my query is correct I'll come to that soon.
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to float.
So this is the problem, I have a temp-table in which ID-number looks like this 9001011234 we can call it A, in the other one that I want to check with it looks like this 900101-1234 and this one for B this is the swedish format for Id-numbers.
So in my condition I want to check this to get the right amount and the correct result.
where A = B
The rest of the query is fine, when I remove this condition it gives me a result. It's just this one bit that is incorrect.

You have a VARCHAR format that can't be trivially transformed to a number. I'd use REPLACE(b,'-','') = a to fix the format, and let SQL Server take care of the rest.

Say:
where A = CAST(REPLACE(B, '-', '') AS float)

You are trying to compare values that are not the same datatype. eg Where 'one' = 1
You will need to convert one of the values to the same datatype as the other.

Related

How to get average of multiple variables

Table name: products,
column names: rice_price, sugar_price
I would like to get the average of both columns separately. For example;
SELECT
AVG(rice_price) avg_rice,
AVG(sugar_price) avg_sugar
FROM
products
If I run this query on SQL server, I get the message below
Msg 8117, Level 16, State 1, Line 4
Operand data type nvarchar is invalid for avg operator.
What could be the solution?
If most of them look like numbers, you could use this, which will exclude the ones that don't convert nicely, by handling them as null:
SELECT
AVG(try_convert(numeric(18,4),rice_price)) avg_rice,
AVG(try_convert(numeric(18,4),sugar_price)) avg_sugar
FROM
products
But you should be changing your datatypes as has been pointed out in the comments. This kind of query will help you discover the ones that aren't good.
SELECT *
FROM products
WHERE rice_price IS NOT NULL
AND try_convert(numeric(18,4),rice_price) IS NULL
SELECT *
FROM products
WHERE sugar_price IS NOT NULL
AND try_convert(numeric(18,4),sugar_price) IS NULL
The IS_NUMERIC function can work for this too, but I find I have switched to using TRY_CONVERT in this situation, because it feels more flexible - I can use whatever data type I need.

SQL Code Error converting data type varchar to float

The following code encounters an error when executed in Microsoft Server Management Studion:
USE [DST]
GO
Select
CAST([Balance] as float)
FROM [RAW_XXX]
WHERE ISNUMERIC(Balance) = 1
Msg 8114, Level 16, State 5, Line 2
Error converting data type varchar to float.
I thought that the ISNUMERIC would exclude anything that can not be cast or converted.
It is a massive database in SQLServer 2012 so I am unsure how to find the data that is causing the error.
Use TRY_CONVERT to flush out the offending records:
SELECT *
FROM [RAW_XXX]
WHERE TRY_CONVERT(FLOAT, Balance) IS NULL;
The issue with your current logic is that something like $123.45 would be true according to ISNUMERIC, but would fail when trying to cast as floating point.
By the way, if you wanted a more bare bones way of finding records not castable to float you could just rely on LIKE:
SELECT *
FROM [RAW_XXX]
WHERE Balance NOT LIKE '%[^0-9.]%' AND Balance NOT LIKE '%.%.%';
The first LIKE condition ensures that Balance consists only of numbers and decimal points, and the second condition ensures that at most one decimal point appears. Checkout the demo below to see this working.
Demo

converted data type (varchar) still shows conversion error

I have a column that can store text but is used to store a number (I did not make the system!) someone has put a blank value in (i.e. not content but not null) and its causing error: -
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric.
I have reduced the issue down to the below: -
SELECT
T1.[FIELD_5],
ISNUMERIC(T1.[FIELD_5]),
NULLIF(T1.[FIELD_5],''),
ISNULL(NULLIF(T1.[FIELD_5],''),0),
CONVERT(DECIMAL(18,5),ISNULL(NULLIF(T1.[FIELD_5],''),0))
FROM
[MyTBL] T1
ORDER BY
ISNUMERIC(T1.[FIELD_5])
The issue data is in [FIELD_5]
I can see SQL sees a value as not numeric
I can see that NULLIF is successfully changing it to a NULL value
I can see the ISNULL is turning the NULLIF result to 0
But the CONVERT on the ISNULL result results in the error message, I would expect it to result in 0.00000
Use try_convert():
SELECT T1.[FIELD_5], ISNUMERIC(T1.[FIELD_5]), NULLIF(T1.[FIELD_5], ''),
COALESCE(NULLIF(T1.[FIELD_5], ''), 0),
TRY_CONVERT(DECIMAL(18, 5), COALESCE(NULLIF(T1.[FIELD_5], ''), 0))
FROM [MyTBL] T1
ORDER BY ISNUMERIC(T1.[FIELD_5]);
try_convert() was introduced in SQL Server 2012. If you are using an earlier version, then you need to use a case expression.
(I switched ISNULL() to COALESCE() because I prefer to use ANSI standard functions where practical.)
There is some non numeric value available you can do that check with case as below:
select convert(decimal(18,5), '')
Throws error as "Error converting data type varchar to numeric.
"
SELECT
T1.[FIELD_5],
ISNUMERIC(T1.[FIELD_5]),
NULLIF(T1.[FIELD_5],''),
ISNULL(NULLIF(T1.[FIELD_5],''),0),
CONVERT(DECIMAL(18,5), iif(isnumeric(ISNULL(T1.[FIELD_5]),'0') > 1,T1.[FIELD_5],'0')
ISNULL(NULLIF(T1.[FIELD_5],''),0))
FROM
[MyTBL] T1
ORDER BY
ISNUMERIC(T1.[FIELD_5])
This was a case of better investigation was needed, I should have realised as in my opinion SQL doesn't lie its normally always user error.
I run it again without the order by clause and then selected the row that would have shown up after the last row that did show up (i.e. that row that caused the error).
[FIELD_5] contained the value 1E-07, an infamous bad import from Excel!
What doesn't add up is why when I had the order by ISNUMERIC on, I did not see this value at the top of the list, only the blank values that were indeed being managed properly.
Question solved, I should have stuck investigating but I think this is worth leaving up to help other investigate in the future.

Return null value or numberic value of 2

I'm needing to return values in SQL query that are either null or 2 for broker reason codes. I've tried using a.BROKER_REASON in (2,null), but it only pulls back 2's. I've tried using "a.BROKER_REASON is null or a.BROKER_REASON = 2" and get error msg "Conversion failed when converting the varchar value '+MULTI' to data type int." Is there an easy way to return rows with null values or values of 2?
That error looks more like your value stored isn't an actual number but rather a small string.
Try:
a.BROKER_REASON is null or a.BROKER_REASON = '2'
If not you may have extra spaces there stored, and can happen depending on storage engines/table definitions, in which case you can do a LTRIM or LEFT (depends on what SQL database you use) or equivalent to trim off excess spaces.

sql convert error on view tables

SELECT logicalTime, traceValue, unitType, entName
FROM vwSimProjAgentTrace
WHERE valueType = 10
AND agentName ='AtisMesafesi'
AND ( entName = 'Hawk-1')
AND simName IN ('TipSenaryo1_0')
AND logicalTime IN (
SELECT logicalTime
FROM vwSimProjAgentTrace
WHERE valueType = 10 AND agentName ='AtisIrtifasi'
AND ( entName = 'Hawk-1')
AND simName IN ('TipSenaryo1_0')
AND CONVERT(FLOAT , traceValue) > 123
) ORDER BY simName, logicalTime
This is my sql command and table is a view table...
each time i put "convert(float...) part " i get
Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to float.
this error...
One (or more) of the rows has data in the traceValue field that cannot be converted to a float.
Make sure you've used the right combination of dots and commas to signal floating point values, as well as making sure you don't have pure invalid data (text for instance) in that field.
You can try this SQL to find the invalid rows, but there might be cases it won't handle:
SELECT * FROM vwSimProjAgentTrace WHERE NOT ISNUMERIC(traceValue)
You can find the documentation of ISNUMERIC here.
If you look in BoL (books online) at the convert command, you see that a nvarchar conversion to float is an implicit conversion. This means that only "float"-able values can be converted into a float. So, every numeric value (that is within the float range) can be converted. A non-numeric value can not be converted, which is quite logical.
Probably you have some non numeric values in your column. You might see them when you run your query without the convert. Look for something like comma vs dot. In a test scenario a comma instead of a dot gave me some problems.
For an example of isnumeric, look at this sqlfiddle