Created
October 29, 2021 20:01
-
-
Save marcomalva/15e489ffa0ff055df85b93bff45b956b to your computer and use it in GitHub Desktop.
[PSQL - Parameterized \COPY TO CSV_FILE]Copy table/query to CSV File #SQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- copy2csv.sql: use psql to copy table or select query to CSV file with source and file as parameter | |
-- | |
-- usage: | |
-- psql -v table_name="<table_name>" -v file_name="<file_name>" -h <host_name> -U <user_name> <db_name> -f copy2csv.sql | |
-- psql -v table_name="dummy" -v file_name="my_dummy.csv" -f copy2csv.sql | |
-- psql -v table_name="(select * from dummy order by birthdate desc)" -v file_name="my_dummy_2.csv" -f copy2csv.sql | |
-- | |
-- idea from: https://postgrespro.com/list/thread-id/1893680 | |
-- see also https://www.postgresqltutorial.com/postgresql-format/ for format command | |
-- | |
-- select format('\copy %I to %L CSV HEADER',:'table_name',:'file_name') as copy_command | |
select format('\copy %s to %L CSV HEADER',:'table_name',:'file_name') as copy_command | |
\gset | |
:copy_command |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment