我正在使用Informix,并在查询中有一个CASE语句,如下所示:
CASE
when l.src_country = 'USA' then tl.cat--prodUSA.description
when l.src_country = 'CAN' AND tl.fuel_type > 0 then tl.fuel_type
when l.src_country = 'CAN' and tl.fuel_type = 0 and tl.cat in ("DEF","DEFD") then 4194304
when l.src_country = 'CAN' and tl.fuel_type = 0 and tl.cat not in ("DEF","DEFD") then tl.fuel_type
else 0
END as product_code
在上面的陈述中,"tl.cat"
属于CHAR类型& "tl.fuel_type"
的类型为INT。
我需要做这样的事情:
CASE
when l.src_country = 'USA' then tl.cat--prodUSA.description
when l.src_country = 'CAN' AND tl.fuel_type > 0 then tl.fuel_type :: CHARACTER
when l.src_country = 'CAN' and tl.fuel_type = 0 and tl.cat in ("DEF","DEFD") then 4194304
when l.src_country = 'CAN' and tl.fuel_type = 0 and tl.cat not in ("DEF","DEFD") then tl.fuel_type :: CHARACTER
else 0
END as product_code
但是当我尝试它时,我得到以下错误:
Corresponding data types must be compatible in CASE expression or DECODE function. [SQL State=IX000, DB Errorcode=-800]
当我尝试这个时:
CASE
when l.src_country = 'USA' then tl.cat--prodUSA.description
when l.src_country = 'CAN' AND tl.fuel_type > 0 then tl.fuel_type :: CHAR
when l.src_country = 'CAN' and tl.fuel_type = 0 and tl.cat in ("DEF","DEFD") then '4194304'
when l.src_country = 'CAN' and tl.fuel_type = 0 and tl.cat not in ("DEF","DEFD") then tl.fuel_type :: CHAR
else '0'
END as product_code
我收到以下错误:
Converted value does not fit into the allotted space
我需要将tl.fuel_type
视为角色。我在这里做错了什么?
答案 0 :(得分:3)
假设我们有一个像这样的表设置:
DROP TABLE IF EXISTS fuel_info;
CREATE TEMP TABLE fuel_info
(
src_country CHAR(3) NOT NULL,
fuel_type INTEGER NOT NULL,
cat CHAR(9) NOT NULL
);
INSERT INTO fuel_info VALUES('USA', 12, 'CAT1');
INSERT INTO fuel_info VALUES('CAN', 10, 'ABC2');
INSERT INTO fuel_info VALUES('CAN', 0, 'DEFD');
INSERT INTO fuel_info VALUES('CAN', 0, 'WXYZ');
INSERT INTO fuel_info VALUES('EUR', 1, 'P3X9');
我们可以调整问题中的表达式来重现问题。例如:
SELECT
CASE
WHEN tl.src_country = 'USA' THEN tl.cat--prodUSA.description
WHEN tl.src_country = 'CAN' AND tl.fuel_type > 0 THEN tl.fuel_type::CHAR
WHEN tl.src_country = 'CAN' AND tl.fuel_type = 0 AND tl.cat IN ("DEF","DEFD") THEN '4194304'
WHEN tl.src_country = 'CAN' AND tl.fuel_type = 0 AND tl.cat NOT IN ("DEF","DEFD") THEN tl.fuel_type::CHAR
ELSE '0'
END AS product_code
FROM fuel_info AS tl;
这会生成SQL -1207: Converted value does not fit into the allotted space
错误。
您可以通过为CHAR
类型转换指定足够大的长度来修复它:
SELECT
CASE
WHEN tl.src_country = 'USA' THEN tl.cat--prodUSA.description
WHEN tl.src_country = 'CAN' AND tl.fuel_type > 0 THEN tl.fuel_type::CHAR(7)
WHEN tl.src_country = 'CAN' AND tl.fuel_type = 0 AND tl.cat IN ("DEF","DEFD") THEN '4194304'
WHEN tl.src_country = 'CAN' AND tl.fuel_type = 0 AND tl.cat NOT IN ("DEF","DEFD") THEN tl.fuel_type::CHAR(7)
ELSE '0'
END AS product_code
FROM fuel_info AS tl;
这有效,产生:
CAT1
10
4194304
0
0