1

I need to run the following statement in PL/pgSQL.

    if file_record.has_recieved_time_column then
        EXECUTE FORMAT('COPY mytemp (columnA, columnB, columnC)
                        FROM %L
                        DELIMITER '',''
                        CSV HEADER;', file_record.file_path);
    elseif file_record.has_header then
        -- dont load columnC
        EXECUTE FORMAT('COPY mytemp (columnA, columnB)
                        FROM %L
                        DELIMITER '',''
                        CSV HEADER;', file_record.file_path);
    else
        -- dont load columnC and the file has no header
        EXECUTE FORMAT('COPY mytemp (columnA, columnB)
                        FROM %L
                        DELIMITER '',''
                        CSV;', file_record.file_path);
    end if;

How can I avoid repeating repeating myself in this code?

2
  • You have three different COPY statements. What do you mean by repeating? Does the function goes on with multiple IF / ELSE ? Commented May 12, 2021 at 11:57
  • 1
    Ideally I would like to build up the query by somehow defining cols = (colA, colB) then do if file_record.has_recieved_time_column: cols += colC and then pass cols as a parameter to the COPY statement and do something similar for the HEADER Commented May 12, 2021 at 12:06

1 Answer 1

1

Try creating variable cols with default values columnA,columnB and then contatenate it with columnC in case you need it, e.g.

  cols := 'columnA, columnB';
  
  IF file_record.has_recieved_time_column THEN
    cols = cols || ',columnC';
  ELSEIF file_record.has_header THEN
    cols = cols || ',columnX';
  ELSE
    .... 
  END IF;
  
  EXECUTE FORMAT('COPY mytemp (%L) FROM %L DELIMITER '',''CSV HEADER;', cols, file_record.file_path);
Sign up to request clarification or add additional context in comments.

3 Comments

This is exactly what I was looking for, is there a way to also solve the header problem in the same way, can I set a header variable which is an empty string and replace it with HEADER then use %L in the same way as you did now?
@sev absolutely. Just replace the HEADER in the COPY string with %L and add an extra variable in the end of the FORMAT command.
@sev something like EXECUTE FORMAT('COPY mytemp (%L) FROM %L DELIMITER '',''CSV %L;', cols, file_record.file_path,header_variable);

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.