Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Format interval date type as a parameter in PostgreSQL function

What is the best way to parameterize interval date type in a PostgreSQL function?. I have the following function

CREATE OR REPLACE FUNCTION testing(
min_time integer
) 
RETURNS void AS
$BODY$
BEGIN
 EXECUTE format('CREATE TABLE foo AS
 SELECT
     gid,
     now() + concat(%s, ' hours')::interval as x,

  FROM foobar
  limit 3  ',min_time  );

 END;
$BODY$
LANGUAGE plpgsql;

Each time I try to execute the function I get the following error ERROR: syntax error at or near "hours"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Single quotes have to be escaped in a string:

CREATE OR REPLACE FUNCTION testing(min_time integer) RETURNS void
   LANGUAGE plpgsql AS
$BODY$
BEGIN
   EXECUTE format(
              'CREATE TABLE foo AS
               SELECT gid,
                      now() + ''%s hours''::interval as x
               FROM foobar
               limit 3',
              min_time
           );
END;
$BODY$;

But actually, you don’t need dynamic SQL for that, and static SQL might be the better choice:

CREATE OR REPLACE FUNCTION testing(min_time integer) RETURNS void
   LANGUAGE plpgsql AS
$BODY$
BEGIN
   CREATE TABLE foo (
      gid bigint NOT NULL,
      x timestamp with time zone NOT NULL
   );

   INSERT INTO foo
   SELECT gid,
          now() + min_time * '1 hour'::interval
   FROM foobar
   limit 3;
END;
$BODY$;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading