CREATE OR REPLACE PROCEDURE public.sp_paidinpaidout(var_storeid int8, var_paidinpaidoutdate varchar, var_filename varchar)
	LANGUAGE plpgsql
AS $$	

BEGIN  
execute 'DROP TABLE IF EXISTS ' || var_filename;
	execute 'CREATE TEMP TABLE ' || var_filename || ' AS
			SELECT pt.paidinouttype AS "Type",  
					a.glaccountname AS "Category",
					c.clerkidname AS "Cashier",
					p."comment" AS "Description" ,
					p.amount AS "Amount",
					r.subject AS "Subject",
					r.department AS "Department"  
			FROM PaidInOut p
				INNER JOIN paidinouttype pt ON pt.paidinouttypeid  = p.paidinouttypeid 
				INNER JOIN cashiers c ON c.clerkkey = p.clerkkey 
				LEFT JOIN accountlisting a ON a.glaccountnumber = p.glaccountnumber 
				LEFT JOIN reimbursement r ON r.paidinoutid = p.paidinoutid 
			WHERE p.businessday = ''' || var_paidinpaidoutdate || ''' 
				AND p.storeid = ' || var_storeid || '
			ORDER BY 1 DESC';
	END;
$$;