[英]How do I merge the multiple If Else using decode in PL/SQL?
The code goes like- 代码像-
If X=x1
then
select a,b
from tab
where zz=yy;
elsif X=x2 or X=x3
then
select a,b
from tab
where zz=yy
and yy= 123;
elsif X=x4
then
select a,b
from tab
where zz=yy
and yy= 456;
end if;
The code in select is being repeated. select中的代码正在重复。 How should i merge it? 我应该如何合并?
At first I thought that a CASE
statement would be appropriate, but then I noticed that your logic always conditionally selects the same two columns a
and b
. 最初,我认为使用CASE
语句是合适的,但是后来我注意到,您的逻辑总是有条件地选择相同的两列a
和b
。 So I think that what you need here is a WHERE
clause to handle all the cases. 因此,我认为您这里需要一个WHERE
子句来处理所有情况。
SELECT a, b
FROM tab
WHERE (x = 'x1' OR
((x = 'x2' OR x = 'x3') AND yy = 123) OR
(x = 'x4' AND yy = 456)) AND
zz = yy
You can use dynamic SQL and compose your query from different parts. 您可以使用动态SQL并从不同部分组成查询。 For example: 例如:
-- common part of query
common_query := 'SELECT a, b FROM tab WHERE zz= yy';
-- set additional condition
IF X=x1 THEN add_where := '';
ELSIF X=x2 OR X=x3 THEN add_where := ' AND yy= 123';
ELSIF X=x4 THEN add_where := ' AND yy= 456';
END IF;
-- compose final query
final_query:= common_query||add_where;
EXECUTE IMMEDIATE final_query;
Of couse when you use dynamic SQL you can use bind variables and you need to remember about return values. 当然,当您使用动态SQL时,可以使用绑定变量,并且需要记住返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.