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.