我需要使用 case 来生成函数的值范围(在DB2中)。
例如,在下面的代码中,我想要(5,6)
select columnA from tableName where columnB in (
(case
when @variable=1 then '4' // specific number
when @variable=2 then '5' //specific number
when @variable=3 then '7,10' // a value range
end)
)
但尝试了几次和其他类似的解决方案,从未得到预期的结果
怎么做?
答案 0 :(得分:1)
首先,In
函数不会读取Case
语句中的多个值。逗号必须在范围内的每个值之后。
其次,您可以在问题中提及有效条件,而不仅仅是1=1
。它总是如此,没有意义。
例:
1)以下查询的输出给出in (5, 6)
select columnA from tableName where columnB in ((case when @variable=1 then 5 end), 6);
2)这只给出了columnB = 5的记录,假设第二个条件是false
。
select columnA from tableName where columnB in ((case when @variable=1 then 5 end), (case when @variable=2 then 6 end));
答案 1 :(得分:0)
尝试类似这样的事情
select columnA from tableName
where columnB in (
select * from table(values 4) tmp(NewCol)
where @variable=1
union all
select * from table(values 5) tmp(NewCol)
where @variable=2
union all
select * from table(values 7, 10) tmp(NewCol)
where @variable=3
)
答案 2 :(得分:0)
除非将字符串转换为rowset,否则不能将字符串作为值范围。我不确定如何在DB2中执行此操作,但我有一些应该可以工作的东西,因为根据文档,DB2确实有unfst()。当然还有其他方法可以创建行集。
SELECT columnA
FROM unnest(array[2,6,8,10], array[7,5,6,28]) --create "temp table" for example purposes
WITH ORDINALITY AS a(columnA, columnB) --alias columns from temp table
WHERE
CASE WHEN true THEN --switch true to some other condition
columnB IN(SELECT * FROM unnest(array[5,6])) --unnest(array[]) will create rowset with 2 rows, each having one column holding integer value
END;
您可能需要从AS a(columnA, columnB)
删除别名,因为我不确定它是否在DB2中有效且我没有找到实时DB2测试人员(在PostgreSQL中我需要测试查询)。