2014-03-13 24 views
0

我需要編寫oracle 查詢(只是查詢) 從表中選擇值,如果沒有找到從其他表中選擇。oracle從表中選擇如果值不存在

任何幫助在pl/sql中做到這一點?

+0

你在尋找一個PL/SQL函數還是隻是一個普通的SQL語句?對數據存在測試的兩個查詢有什麼不同?它是單列還是多列? – woemler

+0

pl/sql查詢,並且它返回很多列 – user3401058

回答

2

SELECT * FROM firstTable

UNION ALL

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

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

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; 
/
相關問題