Laurynas Leskauskas
Laurynas Leskauskas

Reputation: 1

PostgreSQL Export table .csv as current date

I've need to export my table as .csv file, but the name has to be current date.

Currently I am using

COPY public."table" TO 'E:\job.csv' DELIMITER ',' CSV HEADER

What should I do? I tried to look for an answer, but without any luck...

Upvotes: 0

Views: 616

Answers (1)

Alex
Alex

Reputation: 14618

You can always run dynamic SQL

DO $func$
BEGIN
  EXECUTE $$
    COPY public."table" TO 'E:\job_$$ || to_char(CURRENT_DATE, 'YYYY_MM_DD') || $$.csv' DELIMITER ',' CSV HEADER;
  $$;
END;
$func$ LANGUAGE plpgsql;

So you're forming the command as a string, and then passing it to EXECUTE. This works as plpgsql, that you can run either inline, as I've shown, or declared as a function:

CREATE OR REPLACE FUNCTION public.export_table()
RETURNS VOID AS $func$
BEGIN
  EXECUTE $$
    COPY public."table" TO 'E:\job_$$ || to_char(CURRENT_DATE, 'YYYY_MM_DD') || $$.csv' DELIMITER ',' CSV HEADER;
  $$;
END;
$func$ LANGUAGE plpgsql;

Then call it using SELECT public.export_table()

Upvotes: 1

Related Questions