根据标志在 PL/pgsql 中使用不同的列构建查询

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

我需要在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;

如何避免在此代码中重复自己?

尝试使用默认值 columnA,columnB 创建变量 cols,然后在需要时将其与 columnC 连接起来,例如

  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);