我在 SO 社区的帮助下编写了一个存储过程。我拼凑/破解了各种问题的答案来编写我的函数。
但是,当我尝试在数据库(PostgreSQL 8.4)中创建我的函数时,我收到以下错误:
ERROR: syntax error at or near "$4"
LINE 1: ...ank() OVER (ORDER BY $1 , $2 ) / $3 )::int as $4 , $1 ,...
^
和
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
这是我要创建的函数的代码:
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;
谁能理解我为什么会收到这些错误 - 以及如何修复它们?