如何在postgres函数中使用EXECUTE FORMAT ... USING

时间:2012-12-28 06:00:26

标签: postgresql format execute using

CREATE OR REPLACE FUNCTION dummytest_insert_trigger()
  RETURNS trigger AS
$BODY$
DECLARE
v_partition_name    VARCHAR(32);
        BEGIN
        IF NEW.datetime IS NOT NULL THEN
                v_partition_name := 'dummyTest';            
                EXECUTE format('INSERT INTO %I VALUES ($1,$2)',v_partition_name)using NEW.id,NEW.datetime;              
                END IF;                    
           RETURN NULL;
        END;
        $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION dummytest_insert_trigger()
  OWNER TO postgres;

我正在尝试插入使用 插入dummyTest值(1,'2013-01-01 00:00:00 + 05:30');

但它显示错误为

ERROR: function format(unknown) does not exist
SQL state: 42883
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Context: PL/pgSQL function "dummytest_insert_trigger" line 8 at EXECUTE statement

我无法收到错误。

2 个答案:

答案 0 :(得分:10)

您的功能在Postgres 9.0或更高版本中可能如下所示:

CREATE OR REPLACE FUNCTION dummytest_insert_trigger()
  RETURNS trigger AS
$func$
DECLARE
   v_partition_name text := quote_ident('dummyTest');  -- assign at declaration
BEGIN
   IF NEW.datetime IS NOT NULL THEN
      EXECUTE 
      'INSERT INTO ' || v_partition_name || ' VALUES ($1,$2)'
      USING NEW.id, NEW.datetime;              
   END IF;                    

   RETURN NULL;  -- You sure about this?
END
$func$  LANGUAGE plpgsql;

关于RETURN NULL

我建议不要使用混合大小写标识符。使用format( .. %I ..)quote_ident(),您将获得一个名为"dummyTest"的表,您必须在其余的存在时双引号。相关:

请改用小写字母:

quote_ident('dummytest')

只要您拥有静态表名,使用EXECUTE动态SQL就没有意义了。但这可能只是简化的例子?

答案 1 :(得分:0)

您需要将eplxicit强制转换为text

EXECUTE format('INSERT INTO %I VALUES ($1,$2)'::text ,v_partition_name) using NEW.id,NEW.datetime;