2015-02-09 185 views
1

我可以傳遞視圖的名稱作爲函數的參數嗎?例如:將視圖的名稱作爲參數傳遞給函數

CREATE OR REPLACE FUNCTION example_test(test type_view) return void as $$ 
BEGIN 
    start_ts = CLOCK_TIMESTAMP(); 
    REFRESH MATERIALIZED VIEW test; 
    GET DIAGNOSTICS total_rows = ROW_COUNT; 
    INSERT INTO control_dw_monitoring (name, start_time, end_time, total) 
    VALUES ('view points that never contacted', start_ts, CLOCK_TIMESTAMP(), total_rows); 
END 
$$ language plpgsql; 
+0

你需要爲這個動態SQL:http://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL -STATEMENTS-EXECUTING-DYN – 2015-02-09 12:27:10

+0

[那麼你有答案嗎?](http://meta.stackexchange.com/a/5235/169168) – 2015-07-24 03:21:25

回答

0

嘗試以下方法:

CREATE FUNCTION refresh_view_by_name(view_name text) RETURNS VOID AS $$ 
BEGIN 
    EXECUTE 'REFRESH MATERIALIZED VIEW ' || view_name::regclass; 
END 
$$ LANGUAGE PLPGSQL; 
0

的視圖的名稱是一個標識符,而不是一個值。你不能參數化它,所以你需要動態SQL與EXECUTE - 你需要避免SQL注入。首先制定參數爲regclass

CREATE OR REPLACE FUNCTION example_test(_v regclass) 
    RETURNS VOID AS 
$func$ 
DECLARE 
    start_ts timestamptz := clock_timestamp(); 
    total_rows int; 
BEGIN 
    EXECUTE 'REFRESH MATERIALIZED VIEW ' || _v; -- converted to text automatically 
    GET DIAGNOSTICS total_rows = ROW_COUNT; 

    INSERT INTO control_dw_monitoring (name, start_time, end_time, total) 
    VALUES (_v::text, start_ts, clock_timestamp(), total_rows); 
END 
$func$ LANGUAGE plpgsql; 

修正了其中的一些錯誤。
相關答案與更多的解釋:

相關問題