Conversion error when using case statement - Sql Server - sql

I have the following query:
select *,
case when prod='CPU' and quan>1000 then 1000
when prod='MOUSE' and quan>1024 then 1024
when prod='MONITOR' and quan<2 then 2 else quan end as quan
from products_test;
I'm getting the error: Conversion failed when converting the varchar value 'CPU' to data type int.

UPDATE: In light of the following comment from author of question
I changed the code code as described by you, but it's still throwing
an error. "Conversion failed when converting the varchar value
'23787.1' to data type int"
It looks like quan in varchar type rather than numeric and also it with the change in error it has been confirmed that prod is defined as integer.
select *,
case when CAST(prod AS VARCHAR(MAX))='CPU' and CAST(quan as DECIMAL(10,4))>1000 then 1000
when CAST(prod AS VARCHAR(MAX))='MOUSE' and CAST(quan as DECIMAL(10,4))>1024 then 1024
when CAST(prod AS VARCHAR(MAX))='MONITOR' and CAST(quan as DECIMAL(10,4))<2 then 2 else CAST(quan as DECIMAL(10,4)) end as quan
from products_test;
Old answer: Please try this modified query :
select *,
case when CAST(prod AS VARCHAR(MAX))='CPU' and quan>1000 then 1000
when CAST(prod AS VARCHAR(MAX))='MOUSE' and quan>1024 then 1024
when CAST(prod AS VARCHAR(MAX))='MONITOR' and quan<2 then 2 else quan end as quan
from products_test;
if this works successfully, the Prod is in fact defined as int and
you can never get the then (true case) values in CASE statements.
You probably need to compare codes or foreign keys from master table which has values of 'CPU', 'MOUSE' and 'MONITOR' with prod.

Related

Trying to Multiply a Case Statement to a Count

DECLARE #StartDate datetimeoffset,
#EndDate datetimeoffset
SET #StartDate = '2022-03-01 00:00:00.000 +07:00'
SET #EndDate = '2022-03-06 23:59:59.000 +07:00'
SELECT
Records.RecordID,
CONVERT(VARCHAR(10),Records.RecDate AT TIME ZONE 'SE Asia Standard Time',104) AS RecTime,
LocationStr, LocationName,
CONCAT(FirstName,' ',LastName) AS Username ,ProductCodeName,
CASE
WHEN AssetTypeName LIKE '%LTR'
THEN LEFT(AssetTypeName, LEN(AssetTypeName) - 3)
ELSE LEFT(AssetTypeName, LEN(AssetTypeName) - 2)
END * COUNT (ProductCodeName) AS 'SumProduct'
FROM
opendata.records
INNER JOIN
opendata.RecAssets ON Records.RecordId = RecAssets.RecordId
WHERE
(Records.ActionName = 'Fill')
AND (IsDeleted = '0')
AND (Records.RecDate BETWEEN #StartDate and #EndDate)
AND (LocationStr = '3031')
GROUP BY
Records.RecordId, Records.RecDate, LocationStr, LocationName,
CONCAT(FirstName,' ', LastName), ProductCodeName, AssetTypeName
ORDER BY
LocationStr ASC, RecTime ASC, ProductCodeName ASC
Tried to multiply the last to column on my Select statement but failed to do so. I get an error
Conversion failed when converting the ****** value '******' to data type ******.
Furthermore, I tried to convert the case statement to an int but also failed. How can I directly multiply it?
I'm guessing that you're using sql server seeing as it's not oracle and len() is not supported in mySQL or Postgres. You're code calls for an implicit conversion from a numerical value in a char type to a number, for example '123' to 123.
In the following example this doesn't present a problem the first time, but the second time there is a letter in the char value which cannot be converted and throws an error.
I am therefore thinking that you have values of AssetTypeName where there are letters other than in the last 2 characters for non-LTR values of elsewhere in the string for those ending in LTR.
create table test(
AssetTypeName varchar(10),
ProductCodeName int);
insert into test values
('123LTR',1),
('123LTR',1),
('123AB',1);
GO
3 rows affected
select
AssetTypeName,
CASE
WHEN AssetTypeName LIKE '%LTR'
THEN LEFT(AssetTypeName, LEN(AssetTypeName) - 3)
ELSE LEFT(AssetTypeName, LEN(AssetTypeName) - 2)
END * COUNT (ProductCodeName) AS 'SumProduct'
from test
group by AssetTypeName;
GO
AssetTypeName | SumProduct
:------------ | ---------:
123AB | 123
123LTR | 246
insert into test values ('123ABC',1);
GO
1 rows affected
select
AssetTypeName,
CASE
WHEN AssetTypeName LIKE '%LTR'
THEN LEFT(AssetTypeName, LEN(AssetTypeName) - 3)
ELSE LEFT(AssetTypeName, LEN(AssetTypeName) - 2)
END * COUNT (ProductCodeName) AS 'SumProduct'
from test
group by AssetTypeName;
GO
Msg 245 Level 16 State 1 Line 1
Conversion failed when converting the varchar value '123A' to data type int.
db<>fiddle here

Leading 0 on int Column problem SQL Server

I have an issue where I am trying to add a leading 0 to run an output.
SELECT
CASE
WHEN LEN(t.trans_time) = 5
THEN CONCAT(0, [trans_time])
ELSE T.[trans_time]
END AS [TransactionTime]
,RIGHT(CONCAT(0,trans_time),6) AS trans_time
,LEN(T.trans_Time)
,t.trans_time
Why does the case statement not return the leading 0 whereas using:
,RIGHT(CONCAT(0,trans_time),6) AS trans_time
Works no problem.
Case expression return only one type, whereas concat() would return different type & i am assuming trans_time has INT type.
So, you would need to do type conversations :
SELECT (CASE WHEN LEN(t.trans_time) = 5
THEN CONCAT(0, [trans_time])
ELSE CAST(T.[trans_time] AS VARCHAR(255))
END) AS [TransactionTime],
. . .
Another way to do this is to use the format function, wich is available from sql server 2012.
It not only makes the code more readable but will also perform better.
declare #t table (id int)
insert into #t values (90113), (90204), (90207), (90235), (90302), (90318), (90324)
select format(id, '000000') as TransactionTime from #t
this will return
TransactionTime
---------------
090113
090204
090207
090235
090302
090318
090324

SQL SYNTAX - data type error. How to cast?

I have the following code:
CASE WHEN {internalid} = {test} THEN 1 ELSE 0 END;
But when I run it, i received the following error:
Your formula has an error in it. It could resolve to the wrong datatype, use an unknown function, or have a syntax error. Please go back, correct the formula, and re-submit.
Is there a way I can cast it so it will have same data type no matter what?
Thanks
use the cast function
-- CAST ( { expression | NULL } AS data_type [(length)] )
CASE
WHEN CAST ({internalid} as VARCHAR(20)) = CAST({test}as VARCHAR(20))
THEN 1
ELSE 0
END;

Error creating function in DB2 with params

I have a problem with a function in db2
The function finds a record, and returns a number according to whether the first and second recorded by a user
The query within the function is this
SELECT
CASE
WHEN NUM IN (1,2) THEN 5
ELSE 2.58
END AS VAL
FROM (
select ROW_NUMBER() OVER() AS NUM ,s.POLLIFE
from LQD943DTA.CAQRTRML8 c
INNER JOIN LSMODXTA.SCSRET s ON c.MCCNTR = s.POLLIFE
WHERE s.NOEMP = ( SELECT NOEMP FROM LSMODDTA.LOLLM04 WHERE POLLIFE = '0010111003')
) AS T WHERE POLLIFE = '0010111003'
And works perfect
I create the function with this code
CREATE FUNCTION LIBWEB.BNOWPAPOL(POL CHAR)
RETURNS DECIMAL(7,2)
LANGUAGE SQL
NOT DETERMINISTIC
READS SQL DATA
RETURN (
SELECT
CASE
WHEN NUM IN (1,2) THEN 5
ELSE 2.58
END AS VAL
FROM (
select ROW_NUMBER() OVER() AS NUM ,s.POLLIFE
from LQD943DTA.CAQRTRML8 c
INNER JOIN LSMODXTA.SCSRET s ON c.MCCNTR = s.POLLIFE
WHERE s.NOEMP = ( SELECT NOEMP FROM LSMODDTA.LOLLM04 WHERE POLLIFE = POL)
) AS T WHERE POLLIFE = POL
)
The command runs executed properly
WARNING: 17:55:40 [CREATE - 0 row(s), 0.439 secs] Command processed.
No rows were affected
When I want execute the query a get a error
SELECT LIBWEB.BNOWPAPOL('0010111003') FROM DATAS.DUMMY -- dummy has only one row
I get
[Error Code: -204, SQL State: 42704] [SQL0204] BNOWPAPOL in LIBWEB
type *N not found.
I detect, when I remove the parameter the function works fine!
With this code
CREATE FUNCTION LIBWEB.BNOWPAPOL()
RETURNS DECIMAL(7,2)
LANGUAGE SQL
NOT DETERMINISTIC
READS SQL DATA
RETURN (
SELECT
CASE
WHEN NUM IN (1,2) THEN 5
ELSE 2.58
END AS VAL
FROM (
select ROW_NUMBER() OVER() AS NUM ,s.POLLIFE
from LQD943DTA.CAQRTRML8 c
INNER JOIN LSMODXTA.SCSRET s ON c.MCCNTR = s.POLLIFE
WHERE s.NOEMP = ( SELECT NOEMP FROM LSMODDTA.LOLLM04 WHERE POLLIFE = '0010111003')
) AS T WHERE POLLIFE = '0010111003'
)
Why??
This statement:
SELECT LIBWEB.BNOWPAPOL('0010111003') FROM DATAS.DUMMY
causes this error:
[Error Code: -204, SQL State: 42704] [SQL0204] BNOWPAPOL in LIBWEB
type *N not found.
The parm value passed into the BNOWPAPOL() function is supplied as a quoted string with no definition (no CAST). The SELECT statement assumes that it's a VARCHAR value since different length strings might be given at any time and passes it to the server as a VARCHAR.
The original function definition says:
CREATE FUNCTION LIBWEB.BNOWPAPOL(POL CHAR)
The function signature is generated for a single-byte CHAR. (Function definitions can be overloaded to handle different inputs, and signatures are used to differentiate between function versions.)
Since a VARCHAR was passed from the client and only a CHAR function version was found by the server, the returned error fits. Changing the function definition or CASTing to a matching type can solve this kind of problem. (Note that a CHAR(1) parm could only correctly handle a single-character input if a value is CAST.)

Case, Is Null and a parameter

I have a query that i'd like to have display "0" if the "Tip" is "NULL" otherwise just display the tip. This is my query:
SELECT t1.sName ,
t1.sLocationDesc ,
t1.sOtherNumber ,
t1.RegHours ,
t1.OTHours ,
CASE
WHEN t2.EmployeeHours / t3.DepartmentHrs * #Tip IS NULL THEN 0
ELSE t2.EmployeeHours / t3.DepartmentHrs * #Tip
END AS Tip
I receive an error:
Incoming Tabular data stream (TDS) remote procedure call (RPC)
protocal stream is incorrect. Parameter 3 ("#Tip") User-defined type
has an invalid user type specified..
Any help here?
Why do you want to use case
just try this
SELECT t1.sName,
t1.sLocationDesc,
t1.sOtherNumber,
t1.RegHours,
t1.OTHours,
ISNULL(t2.EmployeeHours / t3.DepartmentHrs * #Tip,0) AS 'Tip'
BTW I feel the error is not due to your case statement
Try this:
SELECT t1.sName, t1.sLocationDesc, t1.sOtherNumber, t1.RegHours, t1.OTHours,
CASE WHEN (#Tip IS NULL OR #Tip=0) THEN 0 ELSE
t2.EmployeeHours/t3.DepartmentHrs * #Tip END AS Tip