I need to insert some info I'm reading from a database into a table that belongs to a different one.

I have my info in a RECORD variable, let's call it my_row.

Obviously when I try

SELECT dblink_exec('INSERT INTO remote_table VALUES (my_row.*)');

it doesn't recognize who my_row is.

What other options do I have?

有帮助吗?

解决方案 2

Here's one option:

CREATE TABLE junk(a text, b text,c TIMESTAMP, d hstore);

DO
$BODY$
DECLARE 
RecordVar junk%rowtype;
SqlCommand TEXT:= 'INSERT INTO junk(a,b,c,d) VALUES(';
BEGIN
   RecordVar.a = 'junk''''a';
   RecordVar.b = 'junkb';
   RecordVar.c = NOW();
   RecordVar.d = '"key1"=>"value1"';
   SqlCommand := SqlCommand  || '''' || RecordVar.a || '''' || ',' || '''' || RecordVar.b || '''' || ',' ||'''' || RecordVar.c || '''' || ',' ||'''' || RecordVar.d || '''' || ');';

   RAISE NOTICE 'SQL = %',SqlCommand;

   PERFORM dblink('dblink_logging',SqlCommand);

END;
$BODY$

    Select a,b,c from junk;
    junk'a|junkb|2013-01-28 09:53:22.308|"key1"=>"value1"
    DROP TABLE junk;

其他提示

Try something like:

SELECT dblink_exec('INSERT INTO remote_table VALUES '|| quote_literal(my_row.*));

The idea - to use dynamic SQL. To convert the row to its text representation, escape special chars and form the INSERT statement.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top