我不确定为什么第二个查询失败,我在第二个查询中添加了calLY,因为我不需要子表行数。
SQL正常工作
SELECT count(*) AS rows_cnt
FROM (
SELECT pgc.relname
FROM pg_class pgc
WHERE pgc.oid = 16424
) as tblname
SQL FACING ISSUE
SELECT count(*) AS rows_cnt
FROM ONLY (
SELECT pgc.relname
FROM pg_class pgc
WHERE pgc.oid = 16424
) as tblname
这里" 16424"是我的表OID。
任何人都可以告诉我我的SQL有什么问题。
更新以上问题:
SELECT count(*) AS rows_cnt
FROM ONLY "test-1"
'试验-1'是oid 16424的表名,它工作正常,但是当我使用子查询动态生成表名时,它会失败并出现以下错误,不确定原因。
ERROR: syntax error at or near "SELECT"
LINE 1: (SELECT count(*) AS rows_cnt FROM ONLY ( SELECT pgc.relname ...
^
********** Error **********
ERROR: syntax error at or near "SELECT"
SQL state: 42601
Character: 42
答案 0 :(得分:1)
您无法使用静态SQL执行所需操作,因此需要动态SQL。
最简单的方法是将其放入函数中:
create or replace function get_rowcounts(p_schema text)
returns table (table_name text, row_count bigint)
as
$$
declare
name_rec record;
begin
for name_rec in select t.table_name
from information_schema.tables t
where t.table_schema = p_schema
loop
return query execute format('select %L::text, count(*) from only %I.%I', name_rec.table_name, p_schema, name_rec.table_name);
end loop;
end;
$$
language plpgsql;
可以通过以下方式使用:
select *
from get_rowcounts('public');