【问题标题】:oracle select from table if values not exists如果值不存在,oracle 从表中选择
【发布时间】:2014-03-13 13:16:31
【问题描述】:

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

在 pl/sql 中有什么帮助吗?

【问题讨论】:

  • 您是在寻找 PL/SQL 函数还是只是简单的 SQL 语句?取决于数据存在测试的两个查询有何不同?它是单列,还是许多不同的列?
  • pl/sql查询,返回多列

标签: oracle plsql


【解决方案1】:

SELECT * FROM firstTable

联合所有

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

【讨论】:

    【解决方案2】:

    您可以将 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

    【讨论】:

      【解决方案3】:

      这是一个 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;
      /
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-04
        • 1970-01-01
        • 2021-12-14
        • 2017-09-20
        • 2019-03-05
        • 2015-07-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多