Reputation: 19
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. How should i merge it?
Upvotes: 0
Views: 396
Reputation: 2161
You can use dynamic SQL and compose your query from different parts. 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.
Upvotes: 0
Reputation: 521997
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
. So I think that what you need here is a WHERE
clause to handle all the cases.
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
Upvotes: 1