We Recommend

SQL Cookbook SQL Cookbook
Written in O'Reilly's popular Problem/Solution/Discussion style, the SQL Cookbook is sure to please. Anthony's credo is: "When it comes down to it, we all go to work, we all have bills to pay, and we all want to go home at a reasonable time and enjoy what's still available of our days." The SQL Cookbook moves quickly from problem to solution, saving you time each step of the way.


Posted By

arunpjohny on 10/19/07


Tagged

postgres


Versions (?)


Add a interval to a given date in postgresql


Published in: SQL 


Add a given interval to a date. The intervals can be year, month or day

  1. CREATE OR REPLACE FUNCTION dateadd(diffType Character Varying(15), incrementValue int, inputDate timestamp) RETURNS timestamp AS $$
  2. DECLARE
  3. YEAR_CONST Char(15) := 'year';
  4. MONTH_CONST Char(15) := 'month';
  5. DAY_CONST Char(15) := 'day';
  6.  
  7. dateTemp Date;
  8. intervalValue varchar (100);
  9. BEGIN
  10. IF lower($1) = lower(YEAR_CONST) THEN
  11. dateTemp := inputDate + interval '$2 year';
  12. ELSEIF lower($1) = lower(MONTH_CONST) THEN
  13. dateTemp := inputDate + interval '$2 months';
  14. ELSEIF lower($1) = lower(DAY_CONST) THEN
  15. dateTemp := inputDate + interval '$2 day';
  16. END IF;
  17.  
  18. RETURN dateTemp;
  19. END;
  20. $$ LANGUAGE plpgsql;

Report this snippet 

You need to login to post a comment.