PL / PGSQL函数 - 将TEXT参数传递给date_trunc()

时间:2018-01-23 18:17:10

标签: sql postgresql plpgsql

我想创建一个返回历史日期的简单实用函数。

这是我写的函数:

CREATE FUNCTION testdate(duration TEXT) RETURNS DATE AS $$
BEGIN
 SELECT * FROM date_trunc('day', NOW() - interval duration);
END
$$ LANGUAGE plpgsql;

当我尝试创建该函数时,出现以下错误:

ERROR:  syntax error at or near "duration"
LINE 3:  SELECT * FROM date_trunc('day', NOW() - interval duration);
                                                          ^

当我删除interval关键字时,我可以创建该函数,但是当我尝试按如下方式使用它时:

SELECT * from testdate('1 month');

我收到以下错误消息:

ERROR:  operator does not exist: timestamp with time zone - text
LINE 1: SELECT * FROM date_trunc('day', NOW() - duration)
                                              ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
QUERY:  SELECT * FROM date_trunc('day', NOW() - duration)
CONTEXT:  PL/pgSQL function testdate(text) line 3 at SQL statement

如何正确地将参数传递给date_trunc

1 个答案:

答案 0 :(得分:1)

我假设您尝试这样做:

CREATE or replace FUNCTION testdate(duration interval) RETURNS DATE AS $$
BEGIN
 return (SELECT * FROM date_trunc('day', NOW() - duration));
END
$$ LANGUAGE plpgsql;

用法:

select * from testdate('1 month');
  testdate
------------
 2017-12-23
(1 row)

当然你可以:

CREATE or replace FUNCTION testdate(duration text) RETURNS DATE AS $$
BEGIN
 return (SELECT * FROM date_trunc('day', NOW() - duration::interval));
END
$$ LANGUAGE plpgsql;

带有文字参数,只是为了回答你的问题,但我说适当的数据类型会更加明显...