Warm tip: This article is reproduced from serverfault.com, please click

Is it posible to use queried column_name in INSERT INTO statement?

发布于 2020-11-27 22:40:51

Query:

SELECT string_agg(column_name::text, ',')
FROM information_schema.columns
WHERE table_name = 'my_table' and column_name !='id'

returns list of columns in my_table except 'id':

date_of_birth,first_name,last_name,e_mail

I would like to use this list in INSERT INTO statement when defining columns names. How should I do it, because following don't work.

INSERT INTO my_table2 (
    SELECT string_agg(column_name::text, ',')
    FROM information_schema.columns
    WHERE table_name = 'my_table' and column_name !='id'
    )
VALUES ('a', 'b', ...);

I have changing column count and order in my_table2 and my_table so I must assign names automatically .

Questioner
Algimantas Rainys
Viewed
0
Laurenz Albe 2020-11-28 10:43:27

You have to use dynamic SQL, that is, construct a second query from the result of the first one. There is no way to do it in a single statement.

With psql's \gexec, you could use

SELECT format($$INSERT INTO my_table2 (%s) VALUES ('a', 'b', ...)$$,
              string_agg(quote_ident(column_name), ', ')
             )
FROM information_schema.columns
WHERE table_name = 'my_table'
  AND column_name <> 'id' \gexec