2

I have an SQL Query in PostgreSQL to extract doy (day of year) from dates. My query is:

select extract(doy from date_col) as n
from mytable
order by n

I want to turn it into a function like extract_doy(tablename, date_column_name).
How would I do that?

4

1 回答 1

2

假设您想返回一组双打,这样的事情应该可以工作:

CREATE OR REPLACE FUNCTION tmp_extract_doy(table_name text, column_name text) 
RETURNS SETOF DOUBLE PRECISION
AS
$BODY$
DECLARE
BEGIN
    RETURN QUERY EXECUTE format('SELECT EXTRACT(doy from %I) AS n FROM %I ORDER BY n', column_name, table_name);
END
$BODY$
  LANGUAGE plpgsql
  COST 100;
于 2013-02-07T04:21:42.500 回答