首页 > 解决方案 > 用于加载年度数据的 postgres 函数

问题描述

我有 2 个功能:第一个是接收日期参数的月份数据(任何月份的最后日期),这是截断和加载。第二个是使用上述功能在年表中附加数据的年数据。参数是月数(例如,如果参数为 12,则应为过去 12 个月,如果为 6,则应为过去 6 个月)对于我们的示例,其为 12。

函数 1 调用如下:

select * from fn_monthly('2021-08-31')

对于第二个功能,我们基本上需要根据月份参数进行迭代并执行该功能。其定义如下:

CREATE OR REPLACE FUNCTION fn_yearly(in months int)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
                v_months int = (months*-1)+2;
                v_date date;
    
                
    begin -- executes all code including exception logic
            begin -- returns success if no exception
        
            
            
            
            truncate table yearly_table;
        
        
            for counter in reverse 1..v_months loop
                v_date := (Date_trunc('month', CURRENT_DATE) + interval '% month - 1 day',counter)::date;
-- this should put last date of month in variable v_date
-- example when counter is 1, then v_date = '2021-08-31' 
-- example when counter is 0, then v_date = '2021-07-31' 
-- example when counter is -1, then v_date = '2021-06-30' 
--this is the date I needs to pass into the monthly function

                
                
                select * from fn_monthly(v_date);

                insert into yearly_table(col1,col2) select col1,col2 from monthly_table;
                
            
            end loop;
            
        end; -- returns success if no exception
        $function$
;


当我执行上述函数时,出现以下错误:

ErrorCode:42846, ErrorMsg:cannot cast type record to date

解决此问题的最佳方法是什么?也许其他一些方法。

标签: postgresql

解决方案


错误与此表达式有关:

(Date_trunc('month', CURRENT_DATE) + interval '% month - 1 day',counter)::date

您想格式化间隔,'% month - 1 day',counter但在这种情况下语法不可接受,请使用:

(Date_trunc('month', CURRENT_DATE) + interval '1 month'* counter - interval '1 day')::date

推荐阅读