我想在plpgsql中获取两个日期之间的工作日数。以下是我的代码:
CREATE FUNCTION weekdays(DATE, DATE) RETURNS INTEGER AS
$$
DECLARE
d date := $1;
weekdays integer := 0
BEGIN
LOOP
IF select extract(dow from date d) != 6 or select extract(dow from date d) != 0
weekdays := weekdays +1
END IF
d := d + 1;
EXIT WHEN d > $2;
END LOOP;
RETURN weekdays;
END;
$$
LANGUAGE 'plpgsql' IMMUTABLE;
但是,我一直收到以下错误:
Unterminated dollar quote started at position 56 in SQL CREATE FUNCTION weekdays(DATE, DATE) RETURNS INTEGER AS $$ DECLARE d date := $1. Expected terminating $$
答案 0 :(得分:1)
错误是由;
之后遗失weekdays integer := 0;
引起的。再加上几种这类错误。这将工作:
CREATE OR REPLACE FUNCTION weekdays(date, date)
RETURNS integer AS
$func$
DECLARE
d date := $1;
weekdays int := 0;
BEGIN
LOOP
IF extract(isodow from d) < 6 THEN -- simpler
weekdays := weekdays + 1;
END IF;
d := d + 1;
EXIT WHEN d > $2;
END LOOP;
RETURN weekdays;
END
$func$ LANGUAGE plpgsql IMMUTABLE;
但我建议使用 更简单,更快速的SQL函数 :
CREATE OR REPLACE FUNCTION weekdays_sql(date, date)
RETURNS integer AS
$func$
SELECT count(*)::int
FROM generate_series($1, $2, interval '1d') d
WHERE extract(isodow FROM d) < 6;
$func$ LANGUAGE sql IMMUTABLE;
进一步提高大范围的性能。相关: