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

PL/PGSQL function - passing a TEXT argument to date_trunc()

我想创建一个 returns 历史日期的简单效用函数。

这是我写的函数:

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

我假设您尝试这样做:

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;

带文本参数,只是为了回答你的问题,但我想说适当的数据类型会更有意义...