Sql 使用';当';后功能
我需要在生成in函数(在DB2中)的值范围时使用case 例如,在下面的代码中,我想要(5,6)中的列B 但是尝试了几次和其他类似的解决方案,都没有得到预期的结果Sql 使用';当';后功能,sql,db2,Sql,Db2,我需要在生成in函数(在DB2中)的值范围时使用case 例如,在下面的代码中,我想要(5,6)中的列B 但是尝试了几次和其他类似的解决方案,都没有得到预期的结果 如何执行此操作?首先,函数中的不会读取Case语句中的多个值。逗号必须在范围内的每个值后面 其次,您可以在问题中提及有效条件,而不仅仅是1=1。这总是真的,所以没有意义 示例: 1) 下面查询的输出给出了(5,6)中的 2) 这只给出了columnB=5的记录,假设第二个条件是false select columnA from tab
如何执行此操作?首先,函数中的
不会读取Case
语句中的多个值。逗号必须在范围内的每个值后面
其次,您可以在问题中提及有效条件,而不仅仅是1=1
。这总是真的,所以没有意义
示例:
1) 下面查询的输出给出了(5,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));
试试这样的
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
)
除非将字符串转换为行集,否则不能将其作为值范围。我不知道如何在DB2中做到这一点,但我有一些应该可以工作的东西,因为根据文档,DB2确实有unnest()。当然,还有其他创建行集的方法
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;
您可能需要将别名作为(columnA,columnB)
从中删除,因为我不确定它是否在DB2中工作,而且我还没有找到live DB2 tester(它在我测试查询的PostgreSQL中是必需的)。为什么?此外,1=1始终为真。请解释一下你想做些什么,我的回答是Qu@SamualLee当然,这是在
函数中的中使用用例的方法。
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
)
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;