Possible Duplicate:
Dynamically-generated table-name in PostgreSQL COPY command
I am using the copy to file function in postgresql, which works fine.
Current code looks like this
COPY table
TO 'filename.txt'
This works fine, but I would like to add date to the filename.
So I tried
COPY table
TO 'filename' || CURRENT_DATE || '.txt'
without success.
I have also tried putting it in a query
COPY table
TO (select 'filename' || CURRENT_DATE || '.txt')
Anyone willing to help me out?
EDIT
I think the problem is, that the function COPY TO expects a string, as the destination. And I put in a query, returning a resultset…
As you suspected, the problem is that PostgreSQL is that expecting a string-literal filename, in the form
'filename'orE'filename', rather than an expression (such as a subquery) that would generate a filename asvarcharortextor whatnot. So far as I’m aware, the only work-around is to dynamically generate the entireCOPYstatement, and run it in PL/pgSQL using theEXECUTEcommand. You can create a function like this:and then invoke it like this:
A few notes:
EXECUTEcommand supports aUSINGclause to pass in data; but I’ve just tested, and it seems that something likeEXECUTE 'COPY table TO $1' USING filename;does not work. I assume that this is for more or less the same reason as your original question: the filename has to be specified as a string-literal, not as a substituted parameter. So, be careful with thefilenameyou pass into the function, and make sure it never contains any single-quotes or backslashes or whatnot, or else you’ll accidentally perform a SQL injection attack on yourself.