尝试使用plpgsql将数据插入时间戳字段时出错

时间:2015-06-22 15:55:07

标签: postgresql timestamp plpgsql

我有以下plpgsql功能:

CREATE OR REPLACE FUNCTION test_func(OUT pid bigint)
    RETURNS bigint AS
  $BODY$
    DECLARE
      current_time timestamp with time zone = now();
    BEGIN
      INSERT INTO "TEST"(
        created)
        VALUES (current_time) RETURNING id INTO pid;
    END
  $BODY$
  LANGUAGE plpgsql;

select * from test_func();

上面给出了一个错误:

column "created" is of type timestamp with time zone but expression is of type time with time zone

无功能的插入查询:

INSERT INTO "TEST"(
        created)
        VALUES (now()) RETURNING id INTO pid;

或如果直接使用now()而没有定义变量则可以使用。

1 个答案:

答案 0 :(得分:3)

CURRENT_TIMEreserved word(和一个特殊函数),您不能将其用作变量名。你不需要在这里开始使用变量:

CREATE OR REPLACE FUNCTION test_func(OUT pid bigint) AS
$func$
BEGIN
   INSERT INTO "TEST"(created)
   VALUES (now())
   RETURNING id
   INTO   pid;
END
$func$
LANGUAGE plpgsql;

now()STABLE函数。它不会在同一个事务中发生变化。无需将结果捕获到变量中。