2016-11-23 75 views
1

我想在函數中以兩種不同方式查找數據,並在找到結果後立即返回。plpgsql返回一行或另一行

首先,我想運行一個查詢,如;

select * from company where company.id = x

那麼,如果不返回結果嘗試這樣

select company.* 
    from 
    company 
    join 
    company_alias on company.id = company_alias.company_id 
    where 
    company_alias.company_alias_id = x; 

目前的查詢我有union all

create or replace function get_payer(x int) returns company as $$ 
    select * from company where company.id = x 
    union all 
    select company.* 
    from 
    company 
    join 
    company_alias on company.id = company_alias.company_id 
    where 
    company_alias.company_alias_id = x; 
$$ language sql stable 
set search_path from current; 

這樣做這並未」看起來效率很高,因爲我總是運行兩個查詢。但我不知道如何在plpgsql函數中構造一個條件來處理這個問題。

我已經試過以下的變化沒有任何的運氣

create or replace function payment_claim_payer(x int) returns company as $$ 
declare found_company company; 
begin 

    select * from company where company.id = x into found_company; 

    if not exists found_company then 
    select 
     company.* 
    from 
     company 
    join 
     company_alias on company.id = company_alias.company_id 
    where 
     company_alias.company_alias_id = x into found_company; 
    end if; 

    return found_company; 

end; 
$$ language plpgsql stable 
set search_path from current; 
+0

你想返回'*'或'只是COMPANY_NAME/id'? –

+0

@JuanCarlosOropeza:這是Oracle PL/SQL手冊 - 與Postgres的PL/pgSQL無關 –

回答

1

你最後一次嘗試差點撞上。你需要一個PLPGSQL(不SQL)功能,並應檢查特殊變量found

create or replace function payment_claim_payer(x int) 
returns company language plpgsql as $$ 
declare found_company company; 
begin 
    select * 
    from company 
    where company.id = x 
    into found_company; 

    if not found then 
     select company.* 
     from company 
     join company_alias on company.id = company_alias.company_id 
     where company_alias.company_alias_id = x 
     into found_company; 
    end if; 

    return found_company; 
end; 
$$;