【问题标题】:Error while trying to insert data into timestamp field using plpgsql尝试使用 plpgsql 将数据插入时间戳字段时出错
【发布时间】:2015-09-08 04:09:08
【问题描述】:

我有以下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() 而不定义变量,它可以工作。

【问题讨论】:

    标签: postgresql timestamp plpgsql


    【解决方案1】:

    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 函数。它不会在同一事务中更改。无需将结果捕获到变量中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多