我有以下查询:
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;
我收到错误:将varchar值'CPU'转换为数据类型int时转换失败。
答案 0 :(得分:1)
更新:根据问题作者的以下评论
我改变了你所描述的代码,但它还在抛出 一个错误。 &#34;转换varchar值时转换失败 &#39; 23787.1&#39;到数据类型int&#34;
在quan
类型而不是varchar
中看起来像numeric
,而且在错误更改时,已确认prod
被定义为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;
旧回答:请尝试修改后的查询:
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;
如果此方法成功,
Prod
实际上定义为int
和 您永远无法在then
语句中获得CASE
(真实案例)值。
您可能需要比较主表中的代码或外键,其值为'CPU', 'MOUSE' and 'MONITOR'
和prod。