I have written a stored procedure with the help of the SO community. I have cobbled/hacked together the answers of various questions to write my function.
However, when I try to create my function in the db (PostgreSQL 8.4), I get the following errors:
ERROR: syntax error at or near "$4"
LINE 1: ...ank() OVER (ORDER BY $1 , $2 ) / $3 )::int as $4 , $1 ,...
^
AND
QUERY: SELECT ceil(rank() OVER (ORDER BY $1 , $2 ) / $3 )::int as $4 , $1 , $2 , $5 , $6 , $7 , $8 , $9 , $10 FROM foobar WHERE $2 BETWEEN $11 AND $12 AND $1 = ANY( $13 ) ORDER BY $1 , $2 , $4
CONTEXT: SQL statement in PL/PgSQL function "custom_group" near line 9
This is the code for the function I am trying to create:
CREATE OR REPLACE FUNCTION custom_group(start_date DATE, end_date DATE, grouping_period INTEGER, _ids int[] DEFAULT '{}')
RETURNS TABLE (
grp INTEGER,
id INTEGER,
entry_date DATE,
pop REAL,
hip REAL,
lop REAL,
pcl REAL,
vop BIGINT,
poi BIGINT) AS
$BODY$
BEGIN
IF _ids <> '{}'::int[] THEN -- excludes empty array and NULL
RETURN QUERY
SELECT ceil(rank() OVER (ORDER BY id, entry_date) / $3)::int as grp
,id, entry_date, pop, hip, lop, pcl, vop, poi
FROM foobar
WHERE entry_date BETWEEN start_date AND end_date AND id = ANY(_ids)
ORDER BY id, entry_date, grp ;
ELSE
RETURN QUERY
SELECT ceil(rank() OVER (ORDER BY id, entry_date) / $3)::int as grp
,id, entry_date, pop, hip, lop, pcl, vop, poi
FROM foobar
WHERE entry_date BETWEEN start_date AND end_date
ORDER BY id, entry_date, grp ;
END IF;
END;
$BODY$ LANGUAGE plpgsql;
Can anyone understand why I am getting these errors - and how do I fix them?