Insert from Dynamic Query in Postgres

2019-03-04 02:58发布

问题:

With reference solution I've posted in my previous post resulted in one more situation. While trying to insert into my destination table(schema as below).

-- Table: normalized_transaction

-- DROP TABLE normalized_transaction;

CREATE TABLE normalized_transaction
(
  transaction_id uuid,
  file_id uuid,
  account_number character varying(40),
  currency character varying(3),
  trade_date date,
  value_date date,
  narration character varying(200),
  amount numeric,
  mesitis_account_number character varying(50),
  tag character varying(255),
  supporting_file_id uuid,
  supporting_record_id uuid,
  status integer DEFAULT 0,
  source_type integer,
  record_index integer DEFAULT 0
)

with using a query like

INSERT INTO normalized_transaction(account_number, currency, trade_date)
select gen_Test('english');
fetch all in english;

Result into error:

ERROR:  INSERT has more target columns than expressions
LINE 2: ...NSERT INTO normalized_transaction(account_number, currency, ...
                                                             ^
********** Error **********

ERROR: INSERT has more target columns than expressions
SQL state: 42601
Character: 53



select gen_Test('english');
    fetch all in english;

Just for Reference Output of above Query:

What is appropriate way to insert the result from this into table.

回答1:

You could try like so:

INSERT INTO normalized_transaction(account_number, currency, trade_date)
SELECT foo.*
FROM gen_Test('english') as foo;