尝试使用 plpgsql 将数据插入时间戳字段时出错
Error while trying to insert data into timestamp field using 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()
直接使用而不定义变量它有效。
CURRENT_TIME
is a 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
函数。它不会在同一笔交易中发生变化。无需将结果捕获到变量中。
我有以下 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()
直接使用而不定义变量它有效。
CURRENT_TIME
is a 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
函数。它不会在同一笔交易中发生变化。无需将结果捕获到变量中。