Need help in fixing an issue with passing paramaters to a subquery.
The function shown below works correctly when the parameters are hardcoded in, however when trying to pass the parameters to the crosstab subquery an error is returned the parameters are not available.
I can run the where statement outside the cross table query, but this makes it impossibly slow and unusable.
What I need to know is why and a solution to this if it is possible to do within Postrgesql.
Postgresql Database is verision 9.1
CREATE OR REPLACE FUNCTION f_testfunction1(character varying, date, date)
RETURNS SETOF type_charges AS
$BODY$
DECLARE rec type_charges%ROWTYPE;
DECLARE handling numeric (5,2) := 1.50;
DECLARE banda numeric (5,2) := SELECT pick_rate from pick_costs WHERE pick_band = 'A' AND cust_ref = $1 LIMIT 1;
DECLARE bandb numeric (5,2) := SELECT pick_rate from pick_costs WHERE pick_band = 'C' AND cust_ref = $1 LIMIT 1;
DECLARE bandc numeric (5,2) := SELECT pick_rate from pick_costs WHERE pick_band = 'B' AND cust_ref = $1 LIMIT 1;
BEGIN
FOR rec IN
SELECT ctselect.gdn_custref,gh.gdn_date, gh.gdn_address_name, handling, a, b, c, SUM((a*banda)+(COALESCE(b,0)*bandb)+(COALESCE(c,0)*bandc)+handling) AS ttlpickcost,gh.gdn_method,gh.gdn_postage_chargeout,gh.gdn_postage_chargeto
FROM (SELECT * FROM crosstab($$
SELECT gdn_custref,skref.stockref_pick_charge_code, count(skref.stockref_pick_charge_code) AS ttlcountcode
FROM tbl_pre_gdn_header gh
LEFT JOIN tbl_pre_gdn_body gb ON gh.gdn_gdn = gb.gdn_gdn
JOIN tbl_stockref skref ON skref.stockref_stockref = gb.gdn_stockref
LEFT JOIN tbl_pick_costs pc ON pc.pick_band = skref.stockref_pick_charge_code AND pc.cust_ref = gh.gdn_custcode
WHERE gh.gdn_custcode = $1
AND gh.gdn_date BETWEEN $2 AND $3
GROUP BY gh.gdn_gdn, gdn_custref,gdn_date, gdn_address_name, gdn_postage_chargeto, gdn_method,gdn_postage_actual_cost,
skref.stockref_pick_charge_code, skref.stockref_pick_charge_code
ORDER BY gdn_custref
$$) AS ct(gdn_custref character varying,A bigint, B bigint, C bigint)) as ctselect
LEFT JOIN tbl_pre_gdn_header gh
ON ctselect.gdn_custref = gh.gdn_custref
GROUP BY ctselect.gdn_custref,gh.gdn_date, gh.gdn_address_name,handling, a, b, c,gh.gdn_method,gh.gdn_postage_chargeout,gh.gdn_postage_chargeto
ORDER BY ctselect.gdn_custref LOOP
RETURN NEXT rec;
END LOOP;
RETURN;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
ROWS 1000;