SQL: How to Store Integer value in CASE function in sql? - sql-server

I'm working in a Sybase database.I want the 3rd 'WHEN' statement as Integer as output of Original value(Round((sum(value)*100),1)). How can I achieve this. Thanks in advance.
CASE WHEN Round((sum(value)*100),1)<0 THEN 'Neg'
WHEN Round((sum(value)*100),1)=0 THEN 'N/A'
WHEN Round((sum(value)*100),1)>0 THEN Round((sum(value)*100),1)
END AS RCB
Note: here 3rd row indicating error as it is an integer.The error, I'm getting is :
Error:- Data exception - data type conversion is not possible. In CASE expression, incompatible data type at result expression 3, ROUND(COALESCE ((SUM(MSTR.SUM.value)*100),0),1)
Secondly , I tried with Else statement below.
CASE WHEN Round((sum(value)*100),1)<0 THEN 'Neg'
WHEN Round((sum(value)*100),1)=0 THEN 'N/A'
--WHEN Round((sum(value)*100),1)>0 THEN Round((sum(value)*100),1)
ELSE Round((sum(value)*100),1)
END AS RoRC,
But still getting the same error. Please help me out. Thanks.

You need to cast the number as varchar to match the type of other possible results of CASE statement
CASE WHEN Round((sum(value)*100),1)<0 THEN 'Neg'
WHEN Round((sum(value)*100),1)=0 THEN 'N/A'
WHEN Round((sum(value)*100),1)>0 THEN CAST(Round((sum(value)*100),1) as varchar)

Related

What are all values ISNUMERIC function finds as TRUE in sql server?

Below part of my query was failing initially:
WHEN ISNUMERIC(npx.nvcAnswer) = 1
THEN CASE
WHEN ABS(CONVERT(DECIMAL(38,2),npx.nvcAnswer)) < 1
THEN CONVERT(VARCHAR,CONVERT(DECIMAL(38,2),npx.nvcAnswer))
ELSE npx.nvcAnswer
END
Below was the error we were getting:
com.microsoft.sqlserver.jdbc.SQLServerException: Error converting data type nvarchar to numeric.
rootCause=SQLException #1: errorCode: 8114 sqlState: S0005 message: Error converting data type nvarchar to numeric.
I realized that it considers '.' & '-' as NUMERIC too.
So I added "NOT npx.nvcAnswer in( '.' , '-')" to it and it worked.
WHEN ISNUMERIC(npx.nvcAnswer) = 1 AND NOT npx.nvcAnswer in( '.' , '-')
THEN CASE
WHEN ABS(CONVERT(DECIMAL(38,2),npx.nvcAnswer)) < 1
THEN CONVERT(VARCHAR,CONVERT(DECIMAL(38,2),npx.nvcAnswer))
ELSE npx.nvcAnswer
END
After some day it started failing again with below error.
com.microsoft.sqlserver.jdbc.SQLServerException: Error converting data type nvarchar to numeric.
rootCause=SQLException #1: errorCode: 8114 sqlState: S0005 message: Error converting data type nvarchar to numeric.
Then I changed below block and it worked: (But I failed to find what values were causing this issue)
OLD:
WHEN ABS(CONVERT(DECIMAL(38,2),npx.nvcAnswer)) < 1
THEN CONVERT(VARCHAR,CONVERT(DECIMAL(38,2),npx.nvcAnswer))
NEW:
WHEN ABS(CONVERT(DECIMAL(38,2),PATINDEX('%[^0-9]%', npx.nvcAnswer))) < 1
THEN CONVERT(VARCHAR,CONVERT(DECIMAL(38,2),PATINDEX('%[^0-9]%', npx.nvcAnswer)))
Ask :
What are all values ISNUMERIC function finds as TRUE in sql server?
I will suggest you should your Try_Cast() function instead of using complex logic to check numeric values.
ISNUMERIC returns 1 for some characters that are not numbers, such as plus (+), minus (-), and valid currency symbols such as the dollar sign ($). Please refer below links for further detail -
https://learn.microsoft.com/en-us/sql/t-sql/functions/isnumeric-transact-sql

error converting datatype conversion on single vendoritemnumber in duplicate rows

Sql server query shows error :
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric.
Here is the query:
WITH employee AS (
SELECT distinct vendoritemnumber,VendorItemId,
VendorItemDescription,
VendorItemDescriptionAlias,VendorId,BrgItemId,itemconversionFactor,
orderbyuomid,pricebyuomid,vendorcasedescription,manufacturernumber,skunumber,[weight],
averageweight,currentprice,taxable,[status],createddate,inactivedate,lastpurchaseddate,
lastupdatedby,lastupdateddate,vendorpercent,vendorfreight,brandid,pack,size,inventorycategoryid,
binlocation,inventorylocation,inventorystatus,physicalinventoryconversionfactor,stateswhereused,
conceptwhereused,priceupdatedate,size_uom,pack_uom,isdeleted,'' as id,'' itemid,'' as oldprice,
'' as newprice,'' as dateupdated,'' as weekenddate,'' as lastpurdate
FROM VendorItems WHERE BrgItemId=6056)
SELECT * FROM employee
UNION ALL
SELECT '' as ven,v.VendorItemId,
v.VendorItemDescription,v.VendorItemDescriptionAlias,v.VendorId,v.BrgItemId,v.itemconversionFactor,
v.orderbyuomid,v.pricebyuomid,v.vendorcasedescription,v.manufacturernumber,v.skunumber,v.[weight],
v.averageweight,v.currentprice,v.taxable,v.[status],v.createddate,v.inactivedate,v.lastpurchaseddate,
v.lastupdatedby,v.lastupdateddate,v.vendorpercent,v.vendorfreight,v.brandid,v.pack,v.size,v.inventorycategoryid,
v.binlocation,v.inventorylocation,v.inventorystatus,v.physicalinventoryconversionfactor,v.stateswhereused,
v.conceptwhereused,v.priceupdatedate,v.size_uom,v.pack_uom,v.isdeleted,ph.id,ph.itemid,ph.oldprice,
ph.newprice,ph.dateupdated,ph.weekenddate,brg.lastpurchasedate
from [dbo].[VendorItems] v join PriceHistory ph
on ph.ItemId=v.VendorItemId join brgitems brg on
brg.brgitemid=v.BrgItemId
WHERE v.BrgItemId=6056
group by vendoritemnumber,v.VendorItemId,v.VendorItemDescription,v.VendorItemDescriptionAlias,v.VendorId,v.BrgItemId,v.itemconversionFactor,
v.orderbyuomid,v.pricebyuomid,v.vendorcasedescription,v.manufacturernumber,v.skunumber,v.[weight],
v.averageweight,v.currentprice,v.taxable,v.[status],v.createddate,v.inactivedate,v.lastpurchaseddate,
v.lastupdatedby,v.lastupdateddate,v.vendorpercent,v.vendorfreight,v.brandid,v.pack,v.size,v.inventorycategoryid,
v.binlocation,v.inventorylocation,v.inventorystatus,v.physicalinventoryconversionfactor,v.stateswhereused,
v.conceptwhereused,v.priceupdatedate,v.size_uom,v.pack_uom,v.isdeleted,ph.id,ph.itemid,ph.oldprice,
ph.newprice,ph.dateupdated,ph.weekenddate,brg.lastpurchasedate
I want to show single vendoritemnumber in duplicate rows..Any suggestion??
Where is the error??
SQL Server cannot convert an empty string to NUMERIC data type. For example, the following will yield the same error:
SELECT CONVERT(NUMERIC, '')
Replace empty strings ('') with 0 or NULL.
#manoj .Just FYI to know exact error point , double click on the error in message window .It shows the exact line of code on error, Also try to check if any empty values are there for that column and as mentioned by #Serge SQL throws error while any data type is converted to numeric and if its value is empty. Best solution is to add WHERE clause and filter those cases.

Why is my CASE statement requiring the THEN part to be of data type INT?

I am trying to run a query where the below CASE statement is one of the lines. I'm using Report Builder 3.0.
However, I get an error that says :
Conversion failed when converting the varchar value 'Case 1' to data type int; Microsoft SQL Server, Error: 245".
Why is the CASE statement requiring the THEN part to be an INT data type ?
(CASE
WHEN jobs.Uf_Production_Line = 'LN BM6'
THEN 'Case 1'
ELSE
99999
END
) AS line
When using CASE statement, all result expressions must have the same data type. If not, the result will be converted to the data type with a higher precedence. According to BOL
Returns the highest precedence type from the set of types in
result_expressions and the optional else_result_expression.
And since INT has a higher data type precedence than VARCHAR, your query produces an error:
Conversion failed when converting the varchar value 'Case 1' to data
type int; Microsoft SQL Server, Error: 245".
To fix this, you should convert your ELSE part to VARCHAR.
ELSE '99999'
Because your else uses a value with data type int:
ELSE 99999
You use data types (varchar and int) that can't be exchanged automatically.
An option is to use:
ELSE '99999'
You should use '99999' instead of 99999. All values should be the same datatype in CASE, for now in your ELSE part values is of INT datatype.
Full code should be like:
(CASE WHEN jobs.Uf_Production_Line = 'LN BM6' THEN 'Case 1'
ELSE '99999'
END
) AS line
A case statement can only return one data type. So use the number as varchar:
(CASE WHEN jobs.Uf_Production_Line = 'LN BM6'
THEN 'Case 1'
ELSE '99999'
END
) AS line
OR you can return NULL instead of 9999 if you want to represent it as an invalid value for Line:
(CASE WHEN jobs.Uf_Production_Line = 'LN BM6'
THEN 'Case 1'
ELSE NULL
END
) AS line
Because 99999 is an int. Both cases must return the same data type.

Postgres CASE statement

I cant seem to make the CASE part work
SELECT ROUND((SUM((to_number(g.grade, '9D99') * s.subjunits)))/(SUM(s.subjunits)), 2), CASE WHEN g.grade='DRP' THEN '5.00' END
FROM (grade g
INNER JOIN registration r ON r.grade_id = g.grade_id)
INNER JOIN subject s ON s.subjcode = r.subjcode
WHERE g.grade NOT IN ('INC', 'W', 'INP')
AND r.sy = right(to_char(extract(year from now()- interval '1 year'),'9999'), 4)||'-'||right(to_char(extract(year from now()), '9999'),4)
AND r.sem IN ('1', '2')
AND r.studid='2012-0004'
GROUP BY g.grade;
all I really want is to do is, if a student has a grade of DRP it'll automatically be counted as 5.0 so that the database could include DRP in calculating the GPA.
but it just says
ERROR: invalid input syntax for type numeric: " "
********** Error **********
ERROR: invalid input syntax for type numeric: " "
SQL state: 22P02
currently using postgresql 9.3.2
A case statement returns a value that has nothing inherently to do with any of the values that you fed into it. You seem to be thinking that your case statement will update the value of g.grade. It won't. I think what you want to do is use a case statement in place of the value for g.grade in your first function. Maybe:
SELECT ROUND((SUM((to_number((case when g.grade='DRP' then '5.00' else g.grade end), '9D99') * s.subjunits)))/(SUM(s.subjunits)), 2)
I don't have a copy of Postgres handy so I can't test this, and I'm not familiar with the to_number function (it's been years since I used Postgres). But that's not the point of your question, so if that's not the correct way to call to_number, that's a different issue.
The CASE part is ok (although you miss an ELSE there, it should still work and optionally return NULL).
The error is caused by the TO_NUMBER() function.

Updating an array and converting from varchar to integer

I'm updating an array by adding a varchar to an int4 array. The 'varchar' field is all numbers so I tried casting it to ::integer but it isn't working
update dwh.attr_lookup set kli_tree = array[target_909_kli::integer] || kli_tree
is giving me this error
ERROR: ERROR: invalid input syntax for integer: ""
Query = update
dwh.attr_lookup set kli_tree = array[target_909_kli::integer]
|| kli_tree
What is the proper way to do this?
You're trying to cast an empty string to an integer and that doesn't work:
=> select ''::int;
ERROR: invalid input syntax for integer: ""
LINE 1: select ''::int;
^
You'll have to decide what you want to do with empty strings. If you want to convert them to zeros, then something like this should work:
array[case when target_909_kli = '' then 0 else target_909_kli::integer end]
Obviously your varchar field is not all numbers. There would not be any double quotes in this case - as the error message informs us.
Try giving a full example if the error has not clear by now. Including table definition and sample values.

Resources