CREATE OR REPLACE FUNCTION analyzeTables()
RETURNS INT AS $$
DECLARE
v_rec information_schema.tables%ROWTYPE;
BEGIN
FOR v_rec IN
SELECT *
FROM information_schema.tables mytable
WHERE mytable.TABLE_SCHEMA = 'public'
AND mytable.table_type = 'BASE TABLE'
ORDER BY mytable.table_name
LOOP
ANALYZE v_rec.table_name;
END LOOP;
RETURN 0;
END;
$$
LANGUAGE plpgsql;
SELECT * FROM analyzeTables();
导致ERROR架构" v_rec"不存在SQL语句"ANALYZE v_rec.table_name"
。
正如您所看到的,我试图分析函数中的某些表并且它没有正确解释v_rec,当我尝试返回我要分析的表名时,它认为它是模式名称{{ 1}} fuel_station。尝试使用和不使用mytable别名并使用i.e ANALYZE
和%ROWTYPE
声明同样的错误。我做错了什么?
答案 0 :(得分:0)
尝试动态sql:
CREATE OR REPLACE FUNCTION analyzeTables()
RETURNS INT AS $$
DECLARE
v_rec information_schema.tables%ROWTYPE;
BEGIN
FOR v_rec IN
SELECT *
FROM information_schema.tables mytable
WHERE mytable.TABLE_SCHEMA = 'public'
AND mytable.table_type = 'BASE TABLE'
ORDER BY mytable.table_name
LOOP
execute format('ANALYZE %I',v_rec.table_name);
END LOOP;
RETURN 0;
END;
$$
LANGUAGE plpgsql;
SELECT * FROM analyzeTables();
使用format