Casted timeStamp在PL / pgsql中没有给出正确的结果

时间:2016-10-22 14:57:14

标签: postgresql plpgsql

我是pl / pgsql的新手,我正在尝试执行以下函数,结果为0。

CREATE OR REPLACE FUNCTION public.detectselect (i_channelID integer,te_startTime text,te_endTime text)
RETURNS SETOF detect_inst AS $BODY$
declare
    r detect_inst%rowtype;
    tstz_endTime timestamp without time zone;
    tstz_startTime timestamp without time zone;
BEGIN
    tstz_endTime = to_timestamp(te_endTime,'DD/MM/YYYY hh24:mi:ss')::timestamp without time zone;
    tstz_startTime = to_timestamp(te_startTime,'DD/MM/YYYY hh24:mi:ss')::timestamp without time zone;
    for r in SELECT * FROM detect_inst d WHERE d."ChannelID" = i_channelID AND d."EndTime" >= tstz_startTime AND d."EndTime" < tstz_endTime loop
        return next r;
    end loop;
    RETURN;
END;
$BODY$ LANGUAGE plpgsql;

打电话给

select detectselect(1,'2016-01-21 0:0:0','2016-01-23 0:0:0');

但是当我以这种方式给出静态时间戳值时,它给出了正确的结果

CREATE OR REPLACE FUNCTION public.detectselect (i_channelID integer,te_startTime text,te_endTime text)
RETURNS SETOF detect_inst AS $BODY$
declare
    r detect_inst%rowtype;
    tstz_endTime timestamp without time zone;
    tstz_startTime timestamp without time zone;
BEGIN
    tstz_endTime = to_timestamp(te_endTime,'DD/MM/YYYY hh24:mi:ss')::timestamp without time zone;
    tstz_startTime = to_timestamp(te_startTime,'DD/MM/YYYY hh24:mi:ss')::timestamp without time zone;
    for r in SELECT * FROM detect_inst d WHERE d."ChannelID" = i_channelID AND d."EndTime" >= '2016-01-21 0:0:0' AND d."EndTime" < '2016-01-23 0:0:0' loop
        return next r;
    end loop;
    RETURN;
END;
$BODY$ LANGUAGE plpgsql;

1 个答案:

答案 0 :(得分:1)

您的功能过于复杂。您不需要PL / pgSQL,并且您不需要(慢)光标来返回结果。

它可以简化为一个简单的SQL函数,它也会快得多:

CREATE OR REPLACE FUNCTION public.detectselect (i_channelID integer, te_startTime timestamp, te_endTime timestamp)
   RETURNS SETOF detect_inst AS 
$BODY$
    SELECT * 
    FROM detect_inst d 
    WHERE d."ChannelID" = i_channelID 
    AND d."EndTime" >= te_starttime
    AND d."EndTime" < te_endtime
$BODY$ 
LANGUAGE sql;

然后你打电话给它:

select * 
from detectselect(1, timestamp '2016-01-21 00:00:00', timestamp '2016-01-23 00:00:00' );

您还应该避免使用那些可怕的引用标识符。他们是值得的,他们更麻烦