简体   繁体   中英

PostgreSQL INTERVAL period variable inside a loop

My goal is to calculate the latest seven days of the month within a loop in order to reference some foreign tables names but I'm getting syntax error on the bolded line (day_number_ts) and no idea how to handle it with a different approach.

FOR day_cnt IN 1..7 LOOP
    dayofmonth_ts := TIMESTAMP 'today'::TIMESTAMP;
    **day_number_ts  := dayofmonth_date - (TO_CHAR(day_cnt,99) || ' days')::INTERVAL; ** ----> Syntax error
    day_text := day_number::TEXT;
    IF day_number < 10 THEN 
        day_text := '0'||day_number::text;
    END IF;
    nameoftable := concat('log.pglog_',day_text);
    RAISE NOTICE 'foreign table name: %',nameoftable;
    EXECUTE format ('SELECT * FROM %s',nameoftable::text||' WHERE message LIKE ''AUDIT%''');
END LOOP ;

Use generate_series :

SELECT
    dt
FROM
    generate_series(date_trunc('month', CURRENT_DATE), date_trunc('month', CURRENT_DATE::timestamptz) + '1 month'::interval - '1 day'::interval, '1 day') ast (dt)
ORDER BY
    dt DESC
LIMIT 7;


  dt            
-------------------------
 12/31/2022 00:00:00 PST
 12/30/2022 00:00:00 PST
 12/29/2022 00:00:00 PST
 12/28/2022 00:00:00 PST
 12/27/2022 00:00:00 PST
 12/26/2022 00:00:00 PST
 12/25/2022 00:00:00 PST


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM