如何在 PostgreSql 的 RETURN QUERY EXECUTE 中编写 IF ELSE 语句

How to Write IF ELSE Statements inside RETURN QUERY EXECUTE in PostgreSql

我在 PostgreSQL 11 中的 RETURN QUERY EXECUTE 中编写 IF ELSE 语句时出现语法错误。

CREATE OR REPLACE FUNCTION tds_master.a_report(
    i_entity_id integer,
    i_client_id integer,
    i_branch_id integer,
    i_name text,
    i_finyear integer)
    RETURNS TABLE(employee_name character varying(100), pan character varying(10), optfor115bac character varying(1), 
                  taxable_income numeric, income_tax numeric, credit_us_87a numeric, surcharge numeric, education_cess numeric) 
    LANGUAGE 'plpgsql'AS
$BODY$
BEGIN
   RETURN QUERY EXECUTE 
    
   'if i_name != '' then   
     select
       ed.name as employee_name,
       ed.pan,
       sd.opting_for_us115bac,
       sd.total_taxable_income,
       sd.income_tax_on_total_income,
       sd.rebate_us87a,
       sd.surcharge,
       sd.education_cess
    from tds' || i_finyear || '.saldet sd
       inner join tds' || i_finyear || '.employee_deductee ed on ed.ed_id = sd.employee_id
       where sd.entity_id =  and sd.client_id =  and sd.branch_id =  and upper(ed.name)=upper(i_name);
       
    else
      
    select 
       ed.name as employee_name,
       ed.pan,
       sd.opting_for_us115bac,
       sd.total_taxable_income,
       sd.income_tax_on_total_income,
       sd.rebate_us87a,
       sd.surcharge,
       sd.education_cess
    from tds' || i_finyear || '.saldet sd
       inner join tds' || i_finyear || '.employee_deductee ed on ed.ed_id = sd.employee_id
       where sd.entity_id =  and sd.client_id =  and sd.branch_id = '
  
    USING i_entity_id, i_client_id, i_branch_id;
    
END;
$BODY$;

调用函数:

select * 
from tds_master.a_report(1547,6393,0,'MADAKE VINOD BABURAO',2021);

输出:

阅读评论中提示的 PL/pgSQL 语法。

但是,您可以只合并您的查询变体并使用普通 OR 作为可能为空/空的输入参数 i_name:

CREATE OR REPLACE FUNCTION tds_master.a_report(
    i_entity_id integer,
    i_client_id integer,
    i_branch_id integer,
    i_name text,
    i_finyear integer)
  RETURNS TABLE(employee_name varchar(100), pan varchar(10), optfor115bac varchar(1)
              , taxable_income numeric, income_tax numeric, credit_us_87a numeric
              , surcharge numeric, education_cess numeric) 
  LANGUAGE plpgsql AS
$func$
BEGIN
   RETURN QUERY EXECUTE format(
   $q$
   SELECT ed.name -- AS employee_name
        , ed.pan
        , sd.opting_for_us115bac
        , sd.total_taxable_income
        , sd.income_tax_on_total_income
        , sd.rebate_us87a
        , sd.surcharge
        , sd.education_cess
   FROM   %1$I.saldet sd
   JOIN   %1$I.employee_deductee ed ON ed.ed_id = sd.employee_id
   WHERE  sd.entity_id = 
   AND    sd.client_id = 
   AND    sd.branch_id =        
   AND   (i_name = '' OR  i_name IS NULL OR upper(ed.name) = upper(i_name))  -- !
   $q$, 'tds' || i_finyear::text)
   USING i_entity_id, i_client_id, i_branch_id;
END
$func$;

简单多了。性能相同。

我使用 format(),这是干净的方法。当然,虽然您只连接一个整数值,但普通连接相当安全。