在postgres函数中重用声明的变量

时间:2016-06-10 11:50:37

标签: postgresql variables plpgsql

我正在写一个postgresql函数,我的构造如下:

   CREATE OR REPLACE FUNCTION function_name (argument_list) RETURNS INTEGER [] 
   AS $$
   DECLARE
      --along with other declarations
      _tablename text;
   BEGIN
      -- dynamically construct the intermediate _tablename which gets 
      -- populated
      -- Now I want to use this _tablename in other queries like :
      -- use it in the select from _tablename loop
      -- construct array by selecting a column from this table
      -- and return that array

   END

我该怎么做?我想在函数中的进一步查询中重用声明的变量名。

我完整的postgres功能如下:

 DROP FUNCTION get_value_histogram(BIGINT,BIGINT,BIGINT,INTEGER);
 CREATE OR REPLACE FUNCTION get_value_histogram(customer_id BIGINT, 
 start_time BIGINT, end_time BIGINT, bucket_size INTEGER)
 RETURNS INTEGER[] AS 
 $$
 DECLARE 
    _tablename text;
    _curr_timestamp BIGINT;
    _var1 text;
    _min_value INTEGER;
    _max_value INTEGER;
    _return_array  INTEGER[];
  BEGIN
    -- create an intermediate table with the aggregation of the 
    -- required values. These values then will be passed to the 
    -- Histogram function.
    _var1 := EXTRACT (EPOCH FROM now());
    _var1 := replace(_var1, '.','_');
    _tablename := 'thing_data_' || _var1;
    EXECUTE 'CREATE TABLE ' || _tablename || ' (t_stamp BIGINT,  sum_of_values INTEGER)';

    --insert all the values in this intermediate table
    EXECUTE ' INSERT INTO ' || _tablename || ' ( select t_stamp , sum(data)   from thing_data td, collector_tb ct where td.thingname = 
                ct.collector_name and td.t_stamp BETWEEN  ' ||  quote_literal(start_time) || ' AND ' || quote_literal(end_time) || ' and 
                ct.type like ' || quote_literal('%outlet%') ||' AND  customer_id = ' || customer_id || ' GROUP BY t_stamp)' ; 

    EXECUTE 'select width_bucket(sum_of_values,500, 1000 , 100), count(*) as cnt from ' || _tablename || ' GROUP BY 1 ORDER BY 1' ;
    _return_array :=  array (select cnt from (select width_bucket(sum_of_values,500, 1000 , 100), count(*) as cnt from  _tablename  GROUP BY 1 ORDER BY 1));

    EXECUTE 'DROP TABLE ' || _tablename;

    RETURN _return_array;

END $$ LANGUAGE plpgsql;

当我运行此操作时,我收到一条错误,说明关系" _tablename"不存在

2 个答案:

答案 0 :(得分:1)

只需替换:

 _return_array :=  array (select cnt from (select width_bucket(sum_of_values,500, 1000 , 100), count(*) as cnt from  _tablename  GROUP BY 1 ORDER BY 1) a);

by:

 EXECUTE 'select array (select cnt from (select width_bucket(sum_of_values,500, 1000 , 100), count(*) as cnt from  '|| _tablename ||' GROUP BY 1 ORDER BY 1) a)' into _return_array;

答案 1 :(得分:0)

我认为错误发生在最后一部分:

_return_array :=  array (select cnt from (select width_bucket(sum_of_values,500, 1000 , 100), count(*) as cnt
  from  _tablename  GROUP BY 1 ORDER BY 1));

在这里,您使用_tablename作为实际的文字表名称,而不是变量。