我可以将视图名称作为函数的参数传递吗?例如:
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 :(得分: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;
修复了其他一些错误 相关答案有更多解释: