Function to get year from a date in Postgresql


/ Published in: SQL
Save to your folder(s)

This kind of functions will be use full if we are migrating a database from one provider to another like from MS SQL Server to Postgresql.


Copy this code and paste it in your HTML
  1. CREATE OR REPLACE FUNCTION YEAR (date1 DATE) RETURNS INTEGER AS $$
  2. DECLARE
  3. YEAR_CONST CHARACTER VARYING(15) := 'year';
  4.  
  5. yearPart INTEGER := 0;
  6. yearPartInDoublePrecision DOUBLE PRECISION := 0;
  7. BEGIN
  8.  
  9. yearPartInDoublePrecision := date_part(YEAR_CONST, date1);
  10.  
  11. yearPart := CAST(yearPartInDoublePrecision AS INTEGER);
  12. RETURN yearPart;
  13. END;
  14. $$ LANGUAGE plpgsql;

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.