plpgsql函数出错:数组值必须以“{”或维度信息开头

时间:2013-11-27 18:37:56

标签: function postgresql aggregate-functions plpgsql string-concatenation

我正在尝试格式化此查询的结果:

CREATE OR REPLACE FUNCTION "alarmEventList"(sampleid integer
                            , starttime timestamp without time zone
                            , stoptime timestamp without time zone)
RETURNS text[] AS
$BODY$DECLARE
result text[];
BEGIN
select into result array_agg(res::text) 
from (
    select to_char("Timestamp", 'YYYY-MM-DD HH24:MI:SS')
    ,"AlertLevel"
    ,"Timestamp" - lag("Timestamp") over (order by "Timestamp")
           from "Judgements" 
           WHERE "SampleID" = sampleid
           and "Timestamp" >= starttime 
           and "Timestamp" <= stoptime
         ) res 
    where "AlertLevel" > 0;
    select into result array_to_string(result,',');
return result;
END
$BODY$
LANGUAGE plpgsql VOLATILE

现在没有array_to_string()我得到这样的内容:

{"(\"2013-10-16 15:10:40\",1,00:00:00)","(\"2013-10-16 15:11:52\",1,00:00:48)"}

我想要这样的事情:

 2013-10-16 15:10:40,1,00:00:00 | 2013-10-16 15:11:52,1,00:00:48 |

但是当我运行查询时出现错误:

array value must start with "{" or dimension information

1 个答案:

答案 0 :(得分:1)

实际上想要一个数组类型,但字符串表示。 可以这样实现:

CREATE OR REPLACE FUNCTION "alarmEventList"(sampleid integer
                                          , starttime timestamp
                                          , stoptime timestamp
                                          , OUT result text) AS
$func$
BEGIN

SELECT INTO result string_agg(concat_ws(','
                        ,to_char("Timestamp", 'YYYY-MM-DD HH24:MI:SS')
                        ,"AlertLevel"
                        ,"Timestamp" - ts_lag)
                     , ' | ')
FROM  (
   SELECT "Timestamp"
         ,"AlertLevel"
         ,lag("Timestamp") OVER (ORDER BY "Timestamp") AS ts_lag
   FROM   "Judgements" 
   WHERE  "SampleID"   = sampleid
   AND    "Timestamp" >= starttime 
   AND    "Timestamp" <= stoptime
   ) res
WHERE "AlertLevel" > 0;

END
$func$ LANGUAGE plpgsql

string_agg()concat_ws()上的手册。