Postgres - Passing table name as parameter and store result in file

∥☆過路亽.° 提交于 2019-12-04 06:44:18

问题


    Create Or Replace Function totalRecords (tablename TEXT) Returns integer as $total$
    Declare
      total integer;

      Begin
       select count  (*)  into  total  from''|| tablename ||' 'where now() - cast(date_dimension_year||'-'||date_dimension_month||'-'||date_dimension_day AS date) < INTERVAL '3 months' ;
        RETURN total;
       END;
$total$ LANGUAGE plpgsql;

i have a task which is to create a function which checks the DB for records on given condition if satisfied should output the result to a text file.The above pasted code is what i have been playing around with no sucess.I get syntax error....could anyone guide me on this? I am using postgres DB.


回答1:


I sorted the issue this way

 Begin
 execute 'select count(*) from ' ||tablename||
' where cast(date_dimension_year || ''-'' || date_dimension_month || ''-''||date_dimension_day as date) 
not between (current_date - interval ''13 months'') and current_date' into total ;

I had to assign the integer total towards the end and proper closing of quotation (') worked for me.( I just pasted a portion of the function where i was getting issue)

Thanks for all your help.



来源:https://stackoverflow.com/questions/23292434/postgres-passing-table-name-as-parameter-and-store-result-in-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!