postgresql 通过数据库链接在Postgres中进行动态查询

gk7wooem  于 2022-12-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(126)

我正在尝试创建一个函数,该函数将遍历DBLINK并计算属于用户的对象类型,然后存储该值(我稍后将把这个值插入到一个表中,这样我就可以比较本地数据库和远程数据库中的计数).我可以动态地构建SQL,它看起来是正确的,但是当使用下面的命令通过数据库链接调用它时,我无法让它接受单引号。有没有办法通过数据库链接将其插入到查询中?

DO $$
DECLARE
sqlSmt text;
v_new_count NUMERIC:=0;
item record;

begin
 sqlSmt = null;

 FOR item IN
 (select nsp.nspname schema, cls.relkind obj_type from pg_class cls 
 join pg_roles rol on rol.oid = cls.relowner 
 join pg_namespace nsp on nsp.oid = cls.relnamespace
 where nsp.nspname like 'dwh%' 
 group by nsp.nspname, cls.relkind 
 order by nsp.nspname, cls.relkind limit 10)
 LOOP

 sqlSmt = 'select * from dblink(''old_live'',''select count(*) from pg_class cls
 join pg_roles rol on rol.oid = cls.relowner
 join pg_namespace nsp on nsp.oid = cls.relnamespace
 where nsp.nspname = '''||item.schema||''' and cls.relkind='''||item.obj_type||''') as total_count(total_count numeric)';

 EXECUTE sqlSmt INTO v_new_count;
 raise notice '%', sqlSmt;
 raise notice '%, %, %', item.schema, item.obj_type, v_new_count;

 END LOOP;

END $$;

错误:

ERROR:  syntax error at or near "dwh_10"
LINE 6:  where nsp.nspname = 'dwh_10' and cls.relkind='S') as total_...
                              ^
QUERY:  select * from dblink('old_live','select count(*) from pg_class cls
 join pg_roles rol
 on rol.oid = cls.relowner
 join pg_namespace nsp
 on nsp.oid = cls.relnamespace
 where nsp.nspname = 'dwh_10' and cls.relkind='S') as total_count(total_count numeric)
CONTEXT:  PL/pgSQL function inline_code_block line 27 at EXECUTE
iezvtpos

iezvtpos1#

字符串操作应该可以解决这个问题:
示例:

SELECT '''';
SELECT E'\''; 
SELECT $$'$$;  
SELECT $$ SELECT * FROM test WHERE name='test' ;$$ ; 
 
 sqlSmt = 'select * from dblink(''old_live'',$$select count(*) from pg_class cls
 join pg_roles rol on rol.oid = cls.relowner
 join pg_namespace nsp on nsp.oid = cls.relnamespace
 where nsp.nspname = '''||item.schema||''' and cls.relkind='''||item.obj_type||''') as total_count(total_count numeric)$$;'

$$应该可以解决第二层的字符串操作问题。

相关问题