drop function if exists mmt_staging2.fn_FTWET_RUN;
CREATE OR REPLACE FUNCTION mmt_staging2.fn_FTWET_RUN()
   RETURNS void AS $$
   declare
   	f record;
    w_file_syspk int;
    status text;
   begin
   for f in select distinct a.file_syspk 
		from mmt_staging1.mmt_staging_generic_table a
		where file_format = 'FTWET' order by file_syspk
    loop 
    select f.file_syspk into w_file_syspk;
    perform mmt_staging2.fn_ftwet_trs_block(20,1,'FTWET','FTWET_TRS',w_file_syspk);
    select e.status from mmt_staging2.mmt_DB_Run_Status e where file_syspk = w_file_syspk and sheet_mnemonic ='FTWET_TRS' into status;
    if status = 'success' then
		perform mmt_staging2.fn_FTWET_TRS_ODS(w_file_syspk);
	end if;
	perform mmt_staging2.fn_ftwet_sum_block (20,1,'FTWET','FTWET_SUM',w_file_syspk);
	select e.status from mmt_staging2.mmt_DB_Run_Status e where file_syspk = w_file_syspk and sheet_mnemonic ='FTWET_SUM' into status;
	if status = 'success' then
	perform mmt_staging2.fn_FTWET_SUM_ODS(w_file_syspk);
	perform mmt_staging2.fn_test_output_FTWET(w_file_syspk);
	end if;
    end loop;
end;
$$  LANGUAGE plpgsql;

--select mmt_staging2.fn_FTWET_RUN()