我有以下功能:

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;

或者如果直接使用plpgsql而不定义变量,则可以工作。

最佳答案

CURRENT_TIME是一个reserved 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函数。它不会在同一事务中更改。不需要将结果捕获到变量中。
How do IMMUTABLE, STABLE and VOLATILE keywords effect behaviour of function?

关于postgresql - 尝试使用plpgsql将数据插入时间戳字段时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30984498/

10-11 17:34