Why am I getting `Conversion failed when converting the varchar value 'This is full' to data type int.`? - sql

This code has been working for the past one year but suddenly, we started getting:
Conversion failed when converting the varchar value 'This is full' to data type int
Code:
CASE
WHEN L.Seating_Capacity - COALESCE(TS.TakenSeats,0) = 0 THEN 'This is full'
WHEN l.location = 'MLK High School' AND d.trainingDates = '5/14/2014' THEN 70 - COALESCE(TS.TakenSeats,0)
ELSE CAST(L.Seating_Capacity - COALESCE(TS.TakenSeats,0) AS VARCHAR)
END AS 'AvailableSeats'
Any ideas what went wrong?

Because CASE is an expression - it computes a single value, of a single type. So all of the possible THENs (and the ELSE) must all produce values that can be converted to a single type. You can't have one THEN produce a varchar and a different one produce an int.
And since int has a higher precedence than varchar, that's the single data type that SQL Server tries to convert everything to.
CASE WHEN L.Seating_Capacity - COALESCE(TS.TakenSeats,0) = 0
THEN 'This is full'
WHEN l.location='MLK High School' AND d.trainingDates = '5/14/2014'
THEN CONVERT(varchar(10),70 - COALESCE(TS.TakenSeats,0))
ELSE CONVERT(varchar(10),L.Seating_Capacity - COALESCE(TS.TakenSeats,0))
END AS 'AvailableSeats'

Related

When using cast - error: invalid input syntax for type numeric: "" (postgreSQL)

Duration column in the table is given with 'varchar' data type. It contains decimal values. So I am trying to cast varchar to float/numeric/decimal/double/double precision. But none of those works. why is it not working?
select runner_id,
sum(case when cast(duration as decimal) <> '' then 1
else 0 end) as delivered, count(order_id) as total_orders
from t_runner_orders
group by runner_id
The reason it's not working is because your duration column contains values which cannot be cast to a numeric type. The specific value throwing the error is an empty string. Also, you shouldn't be comparing a numeric type to an empty string.
Also, if you're comparing a varchar column to a character value in your CASE statement, why are you trying to cast it to a numeric type at all?
For what you're doing here, I would just write it as CASE WHEN duration <> '' THEN 1 ELSE 0 END
And if you do need to cast it to a numeric type at some point, the way to do that would be something like CASE WHEN duration = '' THEN NULL ELSE cast(duration AS DECIMAL) END (asuming that empty strings are the only values in your column which cannot be cast to decimal)
The problem is you are doing the CAST before the <> ''. The cast fails as there are empty strings in the field. You have several choices:
Use NULL instead of '' in field.
Do duration <> ''
Last and probably the best long term solution change the column type to numeric.
You can translate '' to null using NULLIF in the cast.
cast(nullif(duration,'') as decimal) is not null
However this will not solve you basic problem which is "varchar' data type. It contains decimal values" NO it does not it contains a string which you hope are decimal values, but nothing prohibits putting 'zero.zero' into it - distinctly not a decimal value. I will go #AdrianKlaver one step further.
3. The only long term solution change the column type to numeric.

CAST and CASE in SQL SELECT statement

I'm trying to return a string when certain conditions are true, but the I'm running into a data type issue... LI.num_seats_pur and LI.num_seats_ret are both smallint data types...
Here's where I'm stuck:
SELECT
CASE
WHEN (LI.num_seats_ret = LI.num_seats_pur)
THEN 'RET'
ELSE (LI.num_seats_pur - LI.num_seats_ret)
END as 'Seats'
FROM T_LINEITEM LI;
I understand that 'RET' is obviously not a smallint, but every combination of CAST I use here is still causing an error. Any ideas?
When using a CASE expression, if the return values have different data types, they will be converted to the one with the higher data type precedence. And since SMALLINT has a higher precedence than VARCHAR, the return value of the ELSE part, 'RET' gets converted to SMALLINT. This will then proceed to a conversion error:
Conversion failed when converting the varchar value 'RET' to data type smallint.
In order to achieve the desired result, you need to CAST the ELSE part to VARCHAR:
SELECT
CASE
WHEN (LI.num_seats_ret = LI.num_seats_pur)
THEN 'RET'
ELSE
CAST((LI.num_seats_pur - LI.num_seats_ret) AS VARCHAR(10))
END AS 'Seats'
FROM T_LINEITEM LI;

SQL Server : conversion error numeric to varchar case

I have this query:
CASE ClaimsFees.TBA
WHEN 0 THEN CAST(IndemnityReserve AS NUMERIC(9,2))
ELSE 'TBA'
END AS 'Reserve Indemnity'
but I always get this error:
Error converting data type varchar to numeric
I have tried to convert TBA as numeric but I can't do this, I also can't convert all the results to varchar because when I transfer to Excel file the number 1.325,27 becomes 132.527,00 with the ##,##0.00 format.
Is there a method in SQL Server that I can use to solve this?
The column can only have one type, and as 'TBA' can only be a string, you'll need to make the numeric a string too.
CASE ClaimsFees.TBA WHEN 0
then cast(cast(IndemnityReserve as NUMERIC(9,2)) as varchar(12))
else 'TBA'
end as 'Reserve Indemnity',

Replacing a calculated field column with a Blank when a NULL is returned?

I'm doing a simple query that uses the DateDiff function to find the number of days between the dates. However, with regards to certain instances, I'd like to populate a blank field (not a null).
Something like this is what I currently have, and it seems to work fine (but it populates a null).
[Test (Years)] = CASE WHEN TYPE IN ('A','B')
THEN NULL ELSE IsNull(CONVERT(decimal(28,12),
(DATEDIFF(d,#StartDate,ExpirationDate)))/365,0) END
Now if I try something like this... which tries to convert all TYPE A and B to populate a blank, I'll get the following error message: Error converting data type varchar to numeric.
[Test (Years)] = CASE WHEN TYPE IN ('A','B')
THEN '' ELSE IsNull(CONVERT(decimal(28,12),
(DATEDIFF(d,#StartDate,ExpirationDate)))/365,0) END
Is there a simple thing I'm missing? I've tried doing the calcualtions without converting to a decimal, but it doesn't seem to work. Any ideas? Thanks
CASE is an expression that returns exactly one value and all of the branches must yield compatible types. A string (even a blank string) is not compatible with a decimal, so you need to do something like:
CASE WHEN ... THEN '' ELSE
CONVERT(VARCHAR(32), COALESCE(CONVERT(DECIMAL(23,12), ... ,0)) END
Note that this hack will only work if you are presenting the data to an end user. If you are trying to store this data in a column or use it in other calculations, it too will be tripped up by the blank string. A number can't be a blank string:
DECLARE #i INT = '';
SELECT #i;
Result:
0
So, if you don't want "empty" numerics to be interpreted as 0, stop being afraid of NULL and if you are dealing with this at presentation time, have the presentation layer present a blank string instead of NULL.

How does one filter based on whether a field can be converted to a numeric?

I've got a report that has been in use quite a while - in fact, the company's invoice system rests in a large part upon this report (Disclaimer: I didn't write it). The filtering is based upon whether a field of type VarChar(50) falls between two numeric values passed in by the user.
The problem is that the field the data is being filtered on now not only has simple non-numeric values such as '/A', 'TEST' and a slew of other non-numeric data, but also has numeric values that seem to be defying any type of numeric conversion I can think of.
The following (simplified) test query demonstrates the failure:
Declare #StartSummary Int,
#EndSummary Int
Select #StartSummary = 166285,
#EndSummary = 166289
Select SummaryInvoice
From Invoice
Where IsNull(SummaryInvoice, '') <> ''
And IsNumeric(SummaryInvoice) = 1
And Convert(int, SummaryInvoice) Between #StartSummary And #EndSummary
I've also attempted conversions using bigint, real and float and all give me similar errors:
Msg 8115, Level 16, State 2, Line 7
Arithmetic overflow error converting
expression to data type int.
I've tried other larger numeric datatypes such as BigInt with the same error. I've also tried using sub-queries to sidestep the conversion issue by only extracting fields that have numeric data and then converting those in the wrapper query, but then I get other errors which are all variations on a theme indicating that the value stored in the SummaryInvoice field can't be converted to the relevant data type.
Short of extracting only those records with numeric SummaryInvoice fields to a temporary table and then querying against the temporary table, is there any one-step solution that would solve this problem?
Edit: Here's the field data that I suspect is causing the problem:
SummaryInvoice
11111111111111111111111111
IsNumeric states that this field is numeric - which it is. But attempting to convert it to BigInt causes an arithmetic overflow. Any ideas? It doesn't appear to be an isolated incident, there seems to have been a number of records populated with data that causes this issue.
It seems that you are gonna have problems with the ISNUMERIC function, since it returns 1 if can be cast to any number type (including ., ,, e0, etc). If you have numbers longer than 2^63-1, you can use DECIMAL or NUMERIC. I'm not sure if you can use PATINDEX to perform an regex look on SummaryInvoice, but if you can, then you should try this:
SELECT SummaryInvoice
FROM Invoice
WHERE ISNULL(SummaryInvoice, '') <> ''
AND CASE WHEN PATINDEX('%[^0-9]%',SummaryInvoice) > 0 THEN CONVERT(DECIMAL(30,0), SummaryInvoice) ELSE -1 END
BETWEEN #StartSummary And #EndSummary
You can't guarantee what order the WHERE clause filters will be applied.
One ugly option to decouple inner and outer.
SELECT
*
FROM
(
Select TOP 2000000000
SummaryInvoice
From Invoice
Where IsNull(SummaryInvoice, '') <> ''
And IsNumeric(SummaryInvoice) = 1
ORDER BY SummaryInvoice
) foo
WHERE
Convert(int, SummaryInvoice) Between #StartSummary And #EndSummary
Another using CASE
Select SummaryInvoice
From Invoice
Where IsNull(SummaryInvoice, '') <> ''
And
CASE WHEN IsNumeric(SummaryInvoice) = 1 THEN Convert(int, SummaryInvoice) ELSE -1 END
Between #StartSummary And #EndSummary
YMMV
Edit: after question update
use decimal(38,0) not int
Change ISNUMERIC(SummaryInvoice) to ISNUMERIC(SummaryInvoice + '0e0')
AND with IsNumeric(SummaryInvoice) = 1, will not short circuit in SQL Server.
But may be you can use
AND (CASE IsNumeric(SummaryInvoice) = 1 THEN Convert(int, SummaryInvoice) ELSE 0 END)
Between #StartSummary And #EndSummary
Your first issue is to fix your database structure so bad data cannot get into the field. You are putting a band-aid on a wound that needs stitches and wondering why it doesn't heal.
Database refactoring is not fun, but it needs to be done when there is a data integrity problem. I assume you aren't really invoicing someone for 11,111,111,111,111,111,111,111,111 or 'test'. So don't allow those values to ever get entered (if you can't change the structure to the correct data type, consider a trigger to prevent bad data from going in) and delete the ones you do have that are bad.