?
Solved

PostgreSQL Custom Function to extract 4 digit year from passed in DATE TIME

Posted on 2007-10-09
2
Medium Priority
?
560 Views
Last Modified: 2012-05-05
In PostgeSQL, I want to create inline functions like I have in other RDBMS'.  

I want to be able to pass in a Date and return the 4 digit year from this function.   The code would be something like this.  

CREATE FUNCTION getYear(TIMESTAMP) RETURNS char(4) AS
SELECT EXTRACT(YEAR FROM $1) LANGUAGE sql;

The use of the function would look something like this:  

SELECT getYear("DateOfBirth") FROM emp;

I have tried to created a function several times, but keep getting errors, please help with my syntax handicap!

Thanks,

FT

0
Comment
Question by:FreightTrain
2 Comments
 
LVL 10

Accepted Solution

by:
ivanovn earned 1600 total points
ID: 20051492
This worked for me:

CREATE OR REPLACE FUNCTION getyear(timestamp with time zone) RETURNS character(4) AS $$
DECLARE
      yr1 character(4);
BEGIN
      SELECT EXTRACT(year from $1) INTO yr1;
      RETURN yr1;
END;
$$ LANGUAGE plpgsql;
0
 
LVL 22

Assisted Solution

by:earth man2
earth man2 earned 400 total points
ID: 20051921
create function getyear( timestamptz ) returns double precision as 'select extract(year from $1)' language sql;
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many developers have database experience, but are new to PostgreSQL. It has some truly inspiring capabilities. I have several years' experience with Microsoft's SQL Server. When I began working with MySQL, I wanted a quick-reference to MySQL (htt…
By, Vadim Tkachenko. In this article we’ll look at ClickHouse on its one year anniversary.
Steps to create a PostgreSQL RDS instance in the Amazon cloud. We will cover some of the default settings and show how to connect to the instance once it is up and running.
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Suggested Courses

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question