oracle如果值不存在则从表中选择

时间:2014-03-13 13:16:32

标签: oracle plsql

我需要写oracle 查询(只是查询) 从表中选择值,如果没有找到,则从另一个表中选择。

在pl / sql中执行此操作的任何帮助吗?

3 个答案:

答案 0 :(得分:2)

  

SELECT * FROM firstTable

     

UNION ALL

     

SELECT * FROM secondTable WHERE(SELECT count(*)FROM FIRST_TABLE)= 0

答案 1 :(得分:0)

您可以将SELECT语句括在一个块中,并为其添加一个异常处理程序。

因此,如果没有从第一个表中选择任何行,则从第二个表中进行选择。结构如下所示:

Begin
    select <many columns> into <many variables or row type>
    From Table1
    where <conditions>;
EXCEPTION
    WHEN NO_DATA_FOUND THEN

    select <many columns> into <many variables or row type>
    From Table2
    Where <Conditions>;
End;

参考文献:

Another related SO question

Exception Handlers

Documentation for the SELECT INTO statement

答案 2 :(得分:0)

以下是将执行测试的PL / SQL函数示例,然后根据测试结果执行辅助查询。您可以根据自己的需要进行调整:

set serveroutput on;

declare
  row_count number;
  column1 varchar(10);
  column2 varchar(10);
  column3 number;

begin

  /*Perform your test*/
  select count(target_column) into row_count
  from my_table
  where condition_column = 'x';

  /*Run your secondary query based on the output of the first*/
  if row_count > 0 then
    select 
      col_x into column1,
      col_y into column2,
      col_z into column3
    from my_other_table_A;
  else
    select 
      col_a into column1,
      col_b into column2,
      col_c into column3
    from my_other_table_B;
  end if;

  /*Show the results*/
  dbms_output.put_line('column1: ' || column1);
  dbms_output.put_line('column2: ' || column2);
  dbms_output.put_line('column3: ' || column3);

end;
/