Skip to content
Advertisement

Building query in PL/pgsql with different columns based on flag

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?

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement