0

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...

1 Answer 1

1

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()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.