My version of Postgres is:
"PostgreSQL 9.4.4, compiled by Visual C++ build 1800, 32-bit"
Let's say I have two tables Table1
and Table2
, which are having column col1
and col2
respectively.
CREATE TABLE Table1(col1 int);
CREATE TABLE Table2(col2 int);
There is another table Table3
storing a formula for migrating data from Table1
to Table2
:
CREATE TABLE Table3 (
tbl_src varchar(200),
col_src varchar(500),
tbl_des varchar(200),
col_des varchar(100),
condition varchar(500)
);
INSERT INTO Table3 (tbl_src, col_src, tbl_des, col_des, condition)
SELECT 'Table1','col1','Table2','col2',NULL
How to compile this formula in a dynamic query and insert into the destination table?
The basic query to build the command dynamically:
SELECT format('INSERT INTO %I (%I) SELECT %I FROM %I'
, tbl_des, col_des, col_src, tbl_src) As sql
FROM table3;
This produces a query like:
INSERT INTO "Table2" (col2) SELECT col1 FROM "Table1"
Note the quoted upper-case spelling. Unlike in SQL commands, where unquoted identifiers are folded to lower-case automatically, the strings in your table are now case-sensitive!
- Are PostgreSQL column names case-sensitive?
I suggest you never double-quote identifiers and use legal, lower-case names exclusively.
To automate:
DO
$$BEGIN
EXECUTE (
SELECT format('INSERT INTO %I (%I) SELECT %I FROM %I'
, tbl_des, col_des, col_src, tbl_src) As sql
FROM table3
-- WHERE table3_id = 123 -- select only *one* row!
);
END$$;
You need to understand the format()
function. Read the manual.
You can wrap this into a plpgsql function as well and pass additional parameters:
- Table name as a PostgreSQL function parameter