简体   繁体   中英

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. 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 . 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM