在ORACLE中使用if语句在FROM语句中选择表

v64noz0r  于 2023-04-05  发布在  Oracle
关注(0)|答案(2)|浏览(221)

请有人帮助我.我想转换这个查询从mybatis到ORACLE

SELECT *
FROM TABLE_A
   <if paramA is not null>
     , ( SELECT *
         FROM TABLE_B
       ) B
   </if>
WHERE ....
   <if paramA is not null>
      A.key = B.key
   </if>

我目前被FROM中IF标记卡住了。

eivgtgni

eivgtgni1#

Oracle不允许有条件地包含表。
一个选项可能是始终连接TABLE_B并在连接条件中过滤参数(作为绑定参数):

SELECT *
FROM   TABLE_A A
       LEFT OUTER JOIN TABLE_B
       ON A.key = B.key AND :paramA IS NOT NULL

这与:paramA绑定变量为NULL时不太一样,TABLE_B列将包含在输出中,但这些TABLE_B列的值将全部为NULL

wqsoz72f

wqsoz72f2#

如果你是以编程方式确定对象名称,你需要使用动态SQL。把动态SQL放在一起并简单地执行,弄清楚你想要如何将数据返回到调用程序或客户端需要更多的思考,因为有多个选项。下面是一个:

CREATE TYPE whatever_rectype IS OBJECT (col1 integer, etc..);
CREATE TYPE whatever_tabtype IS TABLE OF whatever_rectype;

CREATE OR REPLACE FUNCTION whatever (paramA IN varchar2)
RETURN whatever_tabtype PIPELINED
AS
  var_sql varchar2(32767);
  rec_results whatever_rectype;
BEGIN
  var_sql := '
SELECT *
  FROM TABLE_A A';

  IF paramA IS NOT NULL
  THEN
    var_sql := var_sql ||', 
    (SELECT whatever_rectype(col1,col2,etc..)
       FROM TABLE_B
     ) B';
  END IF;

  var_sql := var_sql || '
 WHERE 1=1';

  IF paramA IS NOT NULL
  THEN
    var_sql := var_sql ||'
   AND A.key = B.key';
  END IF;

  OPEN cur_whatever FOR var_sql;

  FETCH cur_whatever INTO rec_results;

  WHILE cur_whatever%FOUND
  LOOP
    PIPE ROW(rec_results);
    FETCH cur_whatever INTO rec_results;
  END LOOP;
END;

执行:

SELECT * 
  FROM TABLE(whatever('myparamAValue'))

在最近的版本中,你可以省去TABLE关键字:

SELECT * 
  FROM whatever('myparamAValue')

相关问题