plpgsql返回一行或另一行

时间:2016-11-23 03:41:14

标签: postgresql 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;

1 个答案:

答案 0 :(得分: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;
$$;