POSTGRES:工作周中的功能问题

时间:2013-09-14 04:06:23

标签: postgresql

我是postgres函数的新手,我正在尝试使用函数处理正常工作时间,并在我合并这两个函数时收到以下错误。

我只想要一个超过2个日期的函数,并在几分钟内返回结果。

第一个功能:获取日期范围内的时间 RUN:SELECT f_work('2013-09-13 06:00','2013-09-13 07:00')
结果:01:00

CREATE OR REPLACE FUNCTION public.f_work (
  t_start timestamp,
  t_end timestamp
)
RETURNS interval AS
$body$
SELECT (count(*) - 1) * interval '1 min'
FROM   (
   SELECT $1 + generate_series(0, (extract(epoch FROM $2 - $1)/60)::integer)
             * interval '1 min' AS t
   ) sub
WHERE  extract(ISODOW from t) > 0
AND    t::time >= '06:00'::time
AND    t::time <  '19:00'::time
$body$
LANGUAGE 'sql'

第二功能:以分钟为单位转换时间 RUN:选择to_min('01:00')
结果:60

CREATE OR REPLACE FUNCTION to_min(t text)
  RETURNS integer AS
$BODY$ 
DECLARE 
    hs INTEGER;
    ms INTEGER;
BEGIN
    SELECT (EXTRACT(HOUR FROM  t::time) * 60) INTO hs; 
    SELECT (EXTRACT(MINUTES FROM t::time)) INTO ms;
    SELECT (hs + ms) INTO ms;
    RETURN ms;
END;
$BODY$
LANGUAGE 'plpgsql';

加入我得到的两个功能和错误:
错误:查询没有结果数据的目的地 提示:如果要放弃SELECT的结果,请改用PERFORM。 语境:PL / pgSQL函数“f_bizwork”第6行SQL语句

CREATE OR REPLACE FUNCTION f_bizwork(t_start timestamp,t_end timestamp)
  RETURNS integer AS
$BODY$
DECLARE 
    hs INTEGER;
    ms INTEGER;
BEGIN
SELECT (count(*) - 1) * interval '1 min'
FROM   (
   SELECT $1 + generate_series(0, (extract(epoch FROM $2 - $1)/60)::integer)
             * interval '1 min' AS t
   ) sub
WHERE extract(ISODOW from t) >0 
AND    t::time >= '06:00'::time
AND    t::time <  '19:01'::time;

SELECT (EXTRACT(HOUR FROM  sub::time) * 60) INTO hs; 
SELECT (EXTRACT(MINUTES FROM sub::time)) INTO ms;
 SELECT (hs + ms) INTO ms;
RETURN ms;
END;
$BODY$
LANGUAGE 'plpgsql';

1 个答案:

答案 0 :(得分:1)

您必须在某处存储第一个查询的结果。否则PostgreSQL不知道如何处理查询结果和报告“查询没有目标”。

这样做:

CREATE OR REPLACE FUNCTION f_bizwork(t_start timestamp,t_end timestamp)
  RETURNS integer AS
$BODY$
DECLARE 
    hs INTEGER;
    ms INTEGER;
    sub time;
BEGIN
SELECT into sub (count(*) - 1) * interval '1 min'
FROM   (
   sELECT $1 + generate_series(0, (extract(epoch FROM $2 - $1)/60)::integer)
             * interval '1 min' AS t
   ) sub
WHERE extract(ISODOW from t) >0 
AND    t::time >= '06:00'::time
AND    t::time <  '19:01'::time;

SELECT (EXTRACT(HOUR FROM  sub::time) * 60) INTO hs; 
SELECT (EXTRACT(MINUTES FROM sub::time)) INTO ms;
 SELECT (hs + ms) INTO ms;
RETURN ms;
END;
$BODY$
LANGUAGE 'plpgsql';

select f_bizwork('2013-09-13 06:00','2013-09-13 07:00')

重要的一行是从SELECT into sub开始的。这会将查询结果存储到变量sub中,该变量在第二个查询中引用。