I am trying to export data from a table to get product wise csv files.I have created a function as below but Postgres throw an error on the variable rec which contains the product when I try to run it. Can anyone assist with troubleshooting my function to find the error? When I was testing it earlier, if I insert the data into a table it works as expected.
CREATE or replace FUNCTION exportdata()
RETURNS SETOF record AS
$$
DECLARE
rec text;
BEGIN
FOR rec IN
(
Select distinct t.products from trndailyprices as t
)
LOOP
Copy (
Select * from trndailyprices as t
where t.products = rec ---1st record is product1
order by t.effectivedate)
To 'C:/testQ/' ||rec || '.csv' With CSV;---expected file is product1.csv for 1st record
END LOOP;
END;
$$ LANGUAGE plpgsql;