4

I have table T1 in database DB1 and table T2 in database DB2, those tables have almost identical sets of columns except column C_additional in T1, which is not present in T2. I need to transfer all the rows from T2 to T1, setting some value of C_additional for each row i insert. For example: T1 and T2 have only one column C1 of type integer and T1 also has column C_additional of type text, so my code looks like this:

INSERT INTO T1
SELECT 
        C1,
        C_additional='needed_value'
FROM dblink(
    'hostaddr=127.0.0.1 port=5432 dbname=DB2 user=postgres password=postgres', 
    'SELECT * FROM T2')
AS T2_row(C1 integer)

I get the following error:

ERROR: column "C_additional" does not exist
SQL state: 42703
Hint: There is a column named "C_additional" in table "T1", but it cannot be referenced from this part of the query.

How can I do the data transfer using SQL, or should I use PG/SQL?

2
  • Show us t1's and t2's definitions. Commented Apr 27, 2016 at 7:15
  • C_additional='needed_value' is a boolean expression that evaluates if the column name C_additional equals the constant 'needed_value'. If you want a column alias use one: 'needed_value' as c_additional Commented Apr 27, 2016 at 7:18

2 Answers 2

3

You can specify the target columns with parenthesis before the select clause:

INSERT INTO T1
(c1, c_additional) -- here
SELECT 
        C1,
        'needed_value' -- just select a constant here
FROM dblink(
    'hostaddr=127.0.0.1 port=5432 dbname=DB2 user=postgres password=postgres', 
    'SELECT * FROM T2')
AS T2_row(C1 integer) 
Sign up to request clarification or add additional context in comments.

Comments

0

Can you try this?

INSERT INTO T1
SELECT 
        C1,
        'needed_value'
FROM dblink(
    'hostaddr=127.0.0.1 port=5432 dbname=DB2 user=postgres password=postgres', 
    'SELECT * FROM T2')
AS T2_row(C1 integer)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.