简体   繁体   中英

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

I want to create a simple utility function that returns a historic date.

This is the function I wrote:

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

When I attempt to create the function, I get the following error:

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

When I remove the interval keyword, I am able to create the function, however when I attempt to use it as follows:

SELECT * from testdate('1 month');

I get the following error message:

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

How do I correctly pass an argument to date_trunc ?

I assume you try to do:

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

with usage:

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

of course you can:

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

with text argument, just to answer your question, but I'd saying appropriate data type would make more sence...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM