I'm getting syntax error while writing IF ELSE statements inside RETURN QUERY EXECUTE in PostgreSQL 11.
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 = $1 and sd.client_id = $2 and sd.branch_id = $3 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 = $1 and sd.client_id = $2 and sd.branch_id = $3'
USING i_entity_id, i_client_id, i_branch_id;
END;
$BODY$;
CALL Function:
select *
from tds_master.a_report(1547,6393,0,'MADAKE VINOD BABURAO',2021);
OUTPUT:

EXECUTEexecutes SQL - and there is noIFin SQL. You need to use anIFinside PL/pgSQL and run different queries.if (...) then execute '...' else execute '...' end if;and (i_name ='' OR upper(ed.name)=upper(i_name))and omit the else part.from tds' || i_finyear || '.saldet sd<<-- you cannot use integers in string concatenation. Also: use the format() function to avoid quoting errors.