2016-06-10 85 views
0

我寫一個PostgreSQL函數聲明的變量和我的結構如下:重用在Postgres的功能

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」不存在

回答

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

由:

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; 
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作爲實際字面表名稱而不是變量。

+0

是的,我知道該查詢是錯誤的,明白_tablename是不是在我的查詢確認。我正在尋找解決方案。謝謝! – neerajdorle