将视图的名称作为参数传递给函数

时间:2015-02-09 12:25:23

标签: postgresql plpgsql dynamic-sql

我可以将视图名称作为函数的参数传递吗?例如:

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;

2 个答案:

答案 0 :(得分:1)

尝试以下方法:

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

答案 1 :(得分:1)

视图的名称是标识符,而不是值。您无法对其进行参数化,因此您需要使用EXECUTE的动态SQL - 并且需要避免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;

修复了其他一些错误 相关答案有更多解释: