PostgreSQL存储过程:如何从变量插入

时间:2015-03-27 20:33:53

标签: stored-procedures postgresql-9.3

我正在尝试编写一个存储过程,它将输入JSON解析为记录并使用JSON内容填充各种表。问题是我无法弄清楚如何在INSERT中使用变量。我的表,类型和存储过程定义为:

REATE TYPE  resource_raw AS (
  "field1" text ,
  "field2" text ,
  "field3" text,
  "field4" text
};
CREATE TABLE IF NOT EXISTS actual_table (
   field1 text,
   field2 text
};

CREATE OR REPLACE FUNCTION discovery_graph.populate_resource(json_in json)
  RETURNS resource_raw AS
 $BODY$DECLARE
   raw_record resource_raw;
 BEGIN   
   SELECT  json_populate_record( NULL::resource_raw, json_in) INTO raw_record;
 INSERT INTO actual_table (field1, field2) SELECT (field1, field2) FROM raw_record;
  RETURN raw_record;
END;
 $BODY$
 LANGUAGE plpgsql VOLATILE;

问题在于,当我执行该过程时,我收到错误:

ERROR:  relation "raw_record" does not exist
LINE 1: ...field1, field2) FROM raw_record

我想知道在使用INSERT变量时我做错了什么?

1 个答案:

答案 0 :(得分:0)

您无法在FROM raw_record中使用INSERT,因为raw_record不是表格。这将运行没有错误:

CREATE OR REPLACE FUNCTION populate_resource(json_in json)
  RETURNS resource_raw AS
 $BODY$DECLARE
   raw_record resource_raw;
 BEGIN   
   SELECT  json_populate_record(NULL::resource_raw, json_in) INTO raw_record;
 INSERT INTO actual_table (field1, field2) (SELECT raw_record.field1, raw_record.field2);
  RETURN raw_record;
END;
 $BODY$
 LANGUAGE plpgsql VOLATILE;

有关文档中变量的更多详细信息,例如:40.10. PL/pgSQL Under the Hood - variable substitution