PostgreSQL – Using COPY Query with Variable Path

plpgsqlpostgresql

I am trying to write a stored procedure that imports a file but what I've noticed is that COPY can be followed by string literal and no variable?

I am trying to achieve something like this

FUNCTION insert_file (IN filepath VARCHAR(255)) ... 
   COPY filepath ...

is it even possible or I need to do some magic?

Best Answer

Yes, for example:

FUNCTION insert_file (IN filepath VARCHAR(255)) ... 
sqltxt:='COPY table_name from '''||filepath||''' with (FORMAT csv)';
execute sqltxt; 

'''||variable||''' will produce 'value' with quotation marks.

'||variable||' will produce the value without quotation marks. usefully for table names and integers for example.

You need to declare sqltxt as text.