我正在编写一个简单的plpgsql函数来测试一个想法,我必须使用information_schema.columns表来动态运行各种表上的指标。该函数工作正常,但是当我在information_schema表中使用info生成要传递给我的函数的表名时,我在标题中收到错误消息:
ERROR: function cannot execute on segment because it accesses relation "my_table"
这是简单的功能(原理验证):
create or replace function count_rows(table_name text, column_name text)
returns bigint as $$
declare
n bigint;
BEGIN
execute 'select count(*) from (select ' || column_name || ' from ' || table_name || ') as t' into n;
return n;
END;
$$ language 'plpgsql';
此查询(以及函数)工作正常:
select * from count_rows('my_table','my_column'); -- works correctly!
但是使用来自information_schema.columns表的输入的此查询失败,并出现上述错误:
select table_name, column_name, count_rows(table_name, column_name) as num_rows
from information_schema.columns where table_name = 'my_table'; -- doesnt work
此错误消息是什么意思?为什么不能以这种方式查询information_schema中列出的表?
答案 0 :(得分:1)
看起来你可能正在使用Greenplum。如果是这样,问题是函数无法访问表。
如果遇到此问题,则必须将函数重写为视图,或者对函数中表select中返回的值进行硬编码。在这种情况下,对结果进行硬编码是没有意义的,因此您需要查看是否可以使视图正常工作。
答案 1 :(得分:0)
使用quote_ident(tablename)& quote_ident(columnname)而不是direct columnname和tablename, 您应该要求访问所有表格