简体   繁体   中英

postgres function not excuting properly: syntax error

    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;

I get error on calling this function I dont know what is the issue here as per logic it should pas the duration as parameter

    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]

on calling the function :

select deleteWeekAggTables('raj_weekly','13 months');

Ok it works now although I have a similar problem with another function :

    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);

The easiest is to pass an interval to the function

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)) ;

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