CREATE OR REPLACE FUNCTION deleteWeekAggTables (tablename TEXT, Duration TEXT) RETURNS INTEGER as $$
DECLARE
startWeek INTEGER;
endWeek INTEGER;
BEGIN
startWeek= EXTRACT(YEAR FROM (CURRENT_DATE - INTERVAL ''||Duration||'') ) * 100 + EXTRACT(WEEK FROM (CURRENT_DATE - INTERVAL ''||Duration||'')) ;
endWeek = EXTRACT(YEAR FROM CURRENT_DATE) * 100 + EXTRACT(WEEK FROM CURRENT_DATE) ;
EXECUTE ' DELETE FROM '||tablename||'
WHERE date_dimension_year * 100 + date_dimension_week
NOT BETWEEN '||startWeek||' AND '||endWeek||' ' ;
RETURN 1;
END;
$$ LANGUAGE plpgsql;
我在调用此函数时遇到错误我不知道这里的问题是什么,因为它应该将持续时间作为参数
6 [SELECT - 0 row(s), 0.000 secs] [Error Code: 0, SQL State: 22007] ERROR: invalid input syntax for type interval: ""
Where: PL/pgSQL function deleteweekaggtables(text,text) line 7 at assignment
... 1 statement(s) executed, 0 row(s) affected, exec/fetch time: 0.000/0.000 sec [0 successful, 0 warnings, 1 errors]
调用函数:
选择deleteWeekAggTables(' raj_weekly',' 13个月');
好吧它现在有效,虽然我有另一个功能的类似问题:
Create Or Replace Function DelAggRecords (tablename TEXT, Duration interval) Returns integer as $$
Begin
execute ' delete from '||tablename|| '
where now() - cast(date_dimension_year||''-''||date_dimension_month||''-''||date_dimension_day AS date) > 'Duration;
RETURN 1;
END;
$$ LANGUAGE plpgsql;
select DelAggRecords('raj_test','13 months'::interval);
答案 0 :(得分:1)
最简单的方法是将间隔传递给函数
select deleteWeekAggTables('raj_weekly','13 months'::interval);
create or replace function deleteweekaggtables (
tablename text, duration interval
) returns integer as $$
startweek =
extract(year from (current_date - duration) ) * 100 +
extract(week from (current_date - duration)) ;