简体   繁体   中英

PSQL to CSV with column alias leads to corrupted file

I managed to use PSQL on Windows to export a SQL query directly into a CSV file, and everything works fine as long as I don't redefine column names with aliases (using AS).

But as soon as I use a column alias, eg:

\copy (SELECT    project AS "ID" FROM    mydb.mytable WHERE  project > 15 ORDER BY project)  TO 'C:/FILES/user/test_SQL2CSV.csv' DELIMITER ',' CSV HEADER

I have unexpected behaviors with the CSV file.

  • In Excel: the CSV is corrupted and is blank
  • In Notepad: the data is present, but with no delimiter or spaces (continous, eg ID27282930...)
  • In Notepad++: the data is well organized in a column

(eg

ID
27
28
29
30
...

)

Is there anything to do so that the exported file can be read directly within Excel (as it happens when I don't use aliases)?

After testing various other configurations of the query, I found the issue. Apparently Excel interprets a file starting with "ID" as some SYLK format instead of CSV... Renaming the column alias to eg "MyID" fixed the issue.

Reference here: annalear.ca/2010/06/10/why-excel-thinks-your-csv-is-a-sylk

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM