【问题标题】:Loop isn't looping from generate_series循环不是从 generate_series 循环的
【发布时间】:2019-01-02 13:41:43
【问题描述】:

我正在创建一个 plpgsql 函数来填充查找表以获取日期信息。我的循环语句只执行第一个日期,而不是循环其他天数。

  DECLARE
startDate ALIAS FOR $1;
endDate ALIAS FOR $2;
currentDate date;
dateDate integer;
yearDate integer;
monthDate integer;
dayDate integer;
weekDate integer;
dayofWeekDate integer;
weekofYearDate integer;
quarterDate integer;

BEGIN
DELETE FROM date_data;

FOR currentDate IN (SELECT * FROM generate_series(startDate::date,endDate::date,'1 day') s(currentDate)) LOOP
    yearDate := (SELECT date_part('year', currentDate));
    monthDate := (SELECT date_part('month', currentDate));
    dayDate := (SELECT date_part('day', currentDate));
    weekDate := (SELECT date_part('week', currentDate));
    dayofWeekDate := (SELECT date_part('dow', currentDate));
    quarterDate := (SELECT date_part('quarter', currentDate));
    weekofYearDate := (SELECT date_part('week', currentDate));
    dateDate := to_char(currentDate,'YYYYMMDD');

    INSERT INTO date_data VALUES ( dateDate, yearDate, monthDate, dayDate, FALSE, dayofWeekDate, FALSE, NULL, FALSE, NULL, weekofYearDate, quarterDate);

    RETURN dateDate;
END LOOP;
END;

我希望它循环插入预期值的时间序列,但它只是插入第一个日期而不是继续。

我正在使用 SELECT add_date_data2('2018-01-01','2019-01-01'); 调用该函数

谢谢。

【问题讨论】:

  • 因为你在循环体中返回。
  • @stickybit 谢谢。搬家确实解决了我的问题。

标签: postgresql plpgsql


【解决方案1】:

您的代码使用了许多显着降低性能的反模式

  1. 循环遍历查询而不是 int 循环

    FOR IN SELECT * FROM generate_series ..
    
  2. 分配中无用的查询

    var := (SELECT expr)
    

因此您的代码可以重写为一个 SQL INSERT

INSERT INTO date_data
   SELECT to_char(d::date,'YYYYMMDD'),
          date_part('year', d::date),
          ...
     FROM generate_series(startdate::date, enddate::date, '1day') g(d);               

或者非常经典:

WHILE d < enddate
LOOP
  yearDate := date_part('year', currentDate);
  monthDate := date_part('month', currentDate);
  dayDate := date_part('day', currentDate);

  INSERT INTO date_data VALUES ( dateDate, yearDate, monthDate, dayDate, FALSE ...
  d := d + interval '1day';
END LOOP;

表达式的计算速度比功能相同的查询快 10 倍 - 因此仅在必要时使用查询 - 更多,您的代码将更具可读性和更清晰。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 2016-05-13
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多