Error converting data type varchar to float - sql

Searched and searched on SO and can't figure it out
Tried CASTING each field as FLOAT to no avail, convert didn't get me any further
How can I get the below case clause to return the value stated in the THEN section?
Error:
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to float.
section of my SQL query that makes it error:
When cust_trendd_w_costsv.terms_code like '%[%]%' and (prod.dbo.BTYS2012.average_days_pay) - (substring(cust_trendd_w_costsv.terms_code,3,2)) <= 5 THEN prod.dbo.cust_trendd_w_costsv.terms_code
average_days_pay = float
terms_code = char
Cheers!

Try to use ISNUMERIC to handle strings which can't be converted:
When cust_trendd_w_costsv.terms_code like '%[%]%'
and (prod.dbo.BTYS2012.average_days_pay) -
(case when isnumeric(substring(cust_trendd_w_costsv.terms_code,3,2))=1
then cast(substring(cust_trendd_w_costsv.terms_code,3,2) as float)
else 0
end)
<= 5 THEN prod.dbo.cust_trendd_w_costsv.terms_code

The issue that you're having is that you're specifically searching for strings that contain a % character, and then converting them (implicitly or explicitly) to float.
But strings containing % signs can't be converted to float whilst they still have a % in them. This also produces an error:
select CONVERT(float,'12.5%')
If you're wanting to convert to float, you'll need to remove the % sign first, something like:
CONVERT(float,REPLACE(terms_code,'%',''))
will just eliminate it. I'm not sure if there are any other characters in your terms_code column that may also trip it up.
You also need to be aware that SQL Server can quite aggressively re-order operations and so may attempt the above conversion on other strings in terms_code, even those not containing %. If that's the source of your error, then you need to prevent this aggressive re-ordering. Provided there are no aggregates involved, a CASE expression can usually avoid the worst of the issues - make sure that all strings that you don't want to deal with are eliminated by earlier WHEN clauses before you attempt your conversion

If your are sure that Substring Part returns a numeric value, You can Cast The substring(....) to Float :
.....and (prod.dbo.BTYS2012.average_days_pay) - (CAST(substring(cust_trendd_w_costsv.terms_code,3,2)) as float ) <= 5 ....

Related

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

Getting an error when casting float to decimal

Moving data from flost to decimal(5,2). largest value I could find int he existing data is 94.23 but when I try to cast to decimal it throws error.
Arithmetic overflow error converting float to data type numeric.
I tried copying straight over without casting, got that error. So then I tried casting first:
CAST(Purity as decimal(5,2))
Same error.
I noticed there are also nulls in there so I tried:
ISNULL(CAST(Purity as decimal(5,2)),0)
Same error.
Did you look for the largest value in the database?
select max(Purity)
from t;
And, in the event that Purity is really a string, you might have other things going on. So, you can try:
select max(convert(purity, 18, 6)) -- or something like this
from t;

SQL CAST String to Decimal

SQL0802 Data conversion or data mapping error
The fields not being CAST are decimals. The fields I am trying to CAST are strings.
I have tried different variations or CAST and CONVERT on this case expression. I'm fairly certain this syntax is correct. I am still getting the error though.
CASE WHEN cpssn=amssn THEN amfnam||amlnam
WHEN cpssn=CAST(maassn as DECIMAL(9)) THEN maafnm||maalnm
WHEN cpssn=CAST(mpssno as DECIMAL(9)) THEN mppfnm||mpplnm
END as Name
One brute force method uses translate():
(CASE WHEN cpssn = amssn THEN amfnam||amlnam
WHEN length(translate(massn, 'a0123456789', 'a')) > 0 THEN NULL
WHEN length(translate(mpssno, 'a0123456789', 'a')) > 0 THEN NULL
WHEN cpssn = CAST(maassn as DECIMAL(9)) THEN maafnm||maalnm
WHEN cpssn = CAST(mpssno as DECIMAL(9)) THEN mppfnm||mpplnm
END) as Name
Note: I am not intimately familiar with translate() in DB2. The above uses an Oracle convention for removing characters, because the third argument cannot be '' in Oracle. It should still work in DB2.
This should work by first guaranteeing that the only characters in the strings are digits. case is processed in sequential order, so the digit checks should be done before the conversion.

add zero and convert as varchar to a flot using a single query

I have data where I need to add leading zeros to it. But the problem is the data type is float. So whenever I add zeros, it automatically omits them. I have tried to add leading zero to it then try to convert it to varchar(50). But the it is giving an error:
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'wallet_sys'.
I have used following query:
select (convert (varchar(50), ('0' + wallet_sys wallet_sys))) from NewSysData1
What have I done wrong?
PS: Some of the sample data are below: 17187383, 87339833, 93838793
I want these to be: 017187383, 087339833, 093838793
You have to add the zero after it's become a string, not before:
select '0' + convert (varchar(50), (wallet_sys)) as wallet_sys from NewSysData1
Normally, most people want to convert to having, say, a fixed width of result, with the appropriate number of leading zeros to make that happen. For that, it's a bit more work:
select RIGHT('0000000000' + convert (varchar(50), (wallet_sys wallet_sys)),10) as wallet_sys
from NewSysData1
Will produce 10 digits, with as many leading zeroes as needed (The number of zeroes in the string literal should be ~equal to the number of desired digits, and this is also the 10 provided at the right hand end of the first line)

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