无法在交叉表函数postgres中传递参数

Unable to pass arguments in crosstab function postgres

我知道我必须将文本传递给 postgres 中的交叉表函数。但不知何故我做不到。我不确定我做错了什么请帮助。这是我要创建的函数

    create or replace function hrms.test2(startdate date)
returns table(
employeeid int,
col1 int,
col2 INT,
col3 int,
col4 int) as
$body$
SELECT * FROM hrms.crosstab(
  $firstquery$ 
  SELECT tms.employeeid,tms.today,count(tms.employeeid) as countid 
  FROM hrms.timesheet as tms
  where dated>=|| quote_literal(startdate) ||
  and dated < ||+ quote_literal(startdate)||::timestamp + '1 MONTH'::INTERVAL
  group by tms.employeeid,tms.today $firstquery$,
  $secquery$ select distinct tms.today 
  from hrms.timesheet as tms$secquery$
)as
finalresult(employeeid int,leave int,present int,absent int, holiday int)
$body$ 
LANGUAGE SQL;

它 运行 成功了,但是当我 运行 它使用像

这样的日期时
select * from hrms.test2('2017-09-01')

我收到一条错误消息说

column startdate doesn't exist

我也尝试了一些替代方案。我不确定我做错了什么请帮助。

你忘了用引号 $firstquery$ 来包装变量,从你的代码中我假设你想要这样的东西:

create or replace function hrms.test2(startdate date)
returns table(
employeeid int,
col1 int,
col2 INT,
col3 int,
col4 int) as
$body$
SELECT * FROM hrms.crosstab(
  $firstquery$ 
  SELECT tms.employeeid,tms.today,count(tms.employeeid) as countid 
  FROM hrms.timesheet as tms
  where dated>=$firstquery$|| quote_literal(startdate) ||$firstquery$
  and dated < $firstquery$||+ quote_literal(startdate)||$firstquery$::timestamp + '1 MONTH'::INTERVAL
  group by tms.employeeid,tms.today $firstquery$,
  $secquery$ select distinct tms.today 
  from hrms.timesheet as tms$secquery$
)as
finalresult(employeeid int,leave int,present int,absent int, holiday int)
$body$ 
LANGUAGE SQL;

您基本上可以使用 $$ 而不是 $firstquery$ 或 $secondquery$。

我没有代表发表评论,所以我留下了回复。