【问题标题】:plpgsql Error: RETURN cannot have a parameter in function returning voidplpgsql 错误:RETURN 在返回 void 的函数中不能有参数
【发布时间】:2013-07-17 11:23:10
【问题描述】:

我正在尝试提取与特定日期相对应的记录计数,以及在数据库中没有对应用户 ID 的用户 ID。这是我试图完成它的方式(使用 plpgsql 但不定义函数:

    DO
    $BODY$
    DECLARE
        a date[]:= array(select distinct start_of_period from monthly_rankings where balance_type=2);
        res int[] = '{}';
    BEGIN
        FOR i IN array_lower(a,1) .. array_upper(a,1)-1
        LOOP
            res:=array_append(res,'SELECT COUNT(user_id) from (select user_id from monthly_rankings where start_of_period=a[i] except select user_id from monthly_rankings where start_of_period=a[i+1]) as b');
                    i:=i+1;
            END LOOP;
            RETURN res;
        $BODY$ language plpgsql

我得到一个错误:无法检索结果:错误:RETURN 在返回 void 的函数中不能有参数 第 11 行:返回资源; 我是这种程序语言的新手,无法发现函数返回 void 的原因。我确实将值分配给变量,并且我声明了空数组,而不是 NULL 数组。是否存在语法或更重要的推理错误?

【问题讨论】:

    标签: sql for-loop syntax plpgsql postgresql-9.2


    【解决方案1】:

    1.) 你不能在DO 语句中使用RETURN。您必须改为CREATE FUNCTION

    2.) 你不需要这些。使用这个查询,它会快一个数量级:

    WITH x AS (
       SELECT DISTINCT start_of_period
             ,rank() OVER (ORDER BY start_of_period) AS rn
       FROM   monthly_rankings
       WHERE  balance_type = 2
       )
    SELECT x.start_of_period, count(*) AS user_ct
    FROM   x
    JOIN   monthly_rankings m USING (start_of_period)
    WHERE  NOT EXISTS (
       SELECT 1
       FROM   x x1
       JOIN   monthly_rankings m1 USING (start_of_period)
       WHERE  x1.rn = x.rn + 1
       -- AND    m1.balance_type = 2 -- only with matching criteria?
       AND    m1.user_id = m.user_id
       )
    -- AND balance_type = 2  -- all user_id from these dates?
    GROUP  BY x.start_of_period
    ORDER  BY x.start_of_period
    

    这包括最后一个符合条件的start_of_period,您可能希望像在您的 plpgsql 代码中一样排除它。

    【讨论】:

      猜你喜欢
      • 2012-12-11
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 2014-04-25
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多