创建规则时出现语法错误

时间:2013-10-09 14:15:10

标签: sql postgresql syntax-error

CREATE OR REPLACE RULE INSERT_part_name AS
   ON INSERT TO partition.part_name
   DO INSTEAD select crm.dblink_exec('crm_server'::text, 'insert into partition.part_name(customerid, partition_name, partition, createdate) values('||new.customerid||','||quote_literal(new.partition_name)||',false'::text ||','||quote_literal(new.createdate))::timestamp without time zone);
ERROR:  syntax error at or near ")"
LINE 3: ...uote_literal(new.createdate))::timestamp without time zone);
                                                                ^

1 个答案:

答案 0 :(得分:0)

不确定在RULE中使用dblink的想法(没有测试)。但是你有一个关闭)太多:

CREATE OR REPLACE RULE INSERT_part_name AS
ON INSERT TO partition.part_name
DO INSTEAD SELECT crm.dblink_exec('crm_server'::text,
   'insert into partition.part_name(customerid, partition_name, partition, createdate)
    values(' || new.customerid || ',' || quote_literal(new.partition_name) || ',false'
    || ',' || quote_literal(new.createdate::timestamp without time zone));

我会使用format()来获得更清晰的代码(需要Postgres 9.1 +):

CREATE OR REPLACE RULE INSERT_part_name AS
ON INSERT TO partition.part_name
DO INSTEAD SELECT crm.dblink_exec('crm_server'::text, format(
 'INSERT INTO partition.part_name(customerid, partition_name, partition, createdate)
  VALUES(%s, %L, false, %L)'
 ,NEW.customerid, NEW.partition_name, NEW.createdate::timestamp));