Reputation: 68426
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
?
Upvotes: 0
Views: 476
Reputation: 51466
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...
Upvotes: 1