PL/pgSQL中的“格式错误的数组文字”错误

PL/pgSQL中的“格式错误的数组文字”错误,sql,postgresql,plpgsql,Sql,Postgresql,Plpgsql,我在PL/pgSQL中遇到一个错误: 错误:数组文字格式错误:2019-11-22 09:18:07.248537详细信息: 数组值必须以{或维度信息开头。上下文: PL/pgSQL函数ChargeLength第11行,用于超选行 请分享您的知识以解决此问题。当您要循环SELECT语句时,需要使用记录变量: CREATE OR REPLACE FUNCTION chargelengtth() RETURNS text AS $$ DECLARE chargetime integer;

我在PL/pgSQL中遇到一个错误:

错误:数组文字格式错误:2019-11-22 09:18:07.248537详细信息: 数组值必须以{或维度信息开头。上下文: PL/pgSQL函数ChargeLength第11行,用于超选行

请分享您的知识以解决此问题。

当您要循环SELECT语句时,需要使用记录变量:

CREATE OR REPLACE FUNCTION chargelengtth() 
  RETURNS text AS
$$
DECLARE 
  chargetime integer;
  othertime integer;
  total integer;
  chargestatus text;
  otherstatus text;
  l_row record; --<< here
BEGIN
  total := 0;
  chargetime := 0;
  FOR l_row IN SELECT * FROM table_name
  LOOP
      RAISE NOTICE 'Stuff: %', l_row;
      IF (l_row.diagnostic = 'Charging' AND chargetime = 0) THEN
          chargetime := extract(epoch from l_row.time);
      END IF;

      IF (l_row.diagnostic != 'Charging') THEN
          othertime := extract(epoch from l_row.time);
          total := total + (othertime - chargetime);
          chargetime := 0;
      END IF;

  END LOOP;
  RETURN to_char(total * interval '1 sec','HH24h MIm');
END$$ LANGUAGE plpgsql;

SELECT chargelengtth()

chargetime的检索有点混乱,因为您似乎依赖于某些行的顺序,但您的查询没有order by。没有order by的限制1基本上是相同的,但是如果您想要可复制的结果,您应该为for loop语句指定order by,这与您的问题无关,但是:您只需要写declare once为什么一开始就使用这样一个低效的循环?你可以用一个查询来完成,不需要循环如何在一个查询中完成,你能给我一个示例吗?请看我的答案-我并不完全清楚你在做什么。如果你提供了一些示例数据和预期的结果,这将很容易r、 DATETIME,C DATETIME,CPE DATETIME,C DATETIME,C DATETIME,CPE DATETIME,PDE对于上述结果,我需要计算第一个和第二个C&CPE记录的时间差为C,第二个和第三个记录的时间差为CPE&C,第三个和第四个记录的时间差为C,并找到C和CPE总的时间差。
CREATE OR REPLACE FUNCTION chargelengtth() 
  RETURNS text AS
$$
DECLARE 
  chargetime integer;
  othertime integer;
  total integer;
  chargestatus text;
  otherstatus text;
  l_row record; --<< here
BEGIN
  total := 0;
  chargetime := 0;
  FOR l_row IN SELECT * FROM table_name
  LOOP
      RAISE NOTICE 'Stuff: %', l_row;
      IF (l_row.diagnostic = 'Charging' AND chargetime = 0) THEN
          chargetime := extract(epoch from l_row.time);
      END IF;

      IF (l_row.diagnostic != 'Charging') THEN
          othertime := extract(epoch from l_row.time);
          total := total + (othertime - chargetime);
          chargetime := 0;
      END IF;

  END LOOP;
  RETURN to_char(total * interval '1 sec','HH24h MIm');
END$$ LANGUAGE plpgsql;

SELECT chargelengtth()
with ct (chargetime) as (
  select time 
  from table_name
  where diagnostic = 'Charging'
  limit 1
)
select sum(t.time - ct.chargetime) 
from the_table t
  cross join ct
where t.diagnostic <> 'Charging'