SELECt string_agg('SELECT student_name, ''' || c.oid::regclass || ''' AS tbl, pid FROM ' || c.oid::regclass || $$ WHERe student_name = 'John Doe'$$ , E'nUNIOn ALLn')FROM pg_namespace nJOIN pg_class c ON c.relnamespace = n.oidWHERe n.nspname = 'public' -- schema name where your tables lieAND c.relname LIKE 't%' -- and / or filter table namesAND EXISTS ( SELECt 1 FROM pg_attribute WHERe attrelid = c.oid AND attname = 'student_name' -- make sure column exists AND NOT attisdropped -- and is alive );
产生查询字符串:
SELECT student_name, 'tbl1' AS tbl, pid FROM tbl1 WHERe student_name = 'John Doe'UNIOn ALLSELECt student_name, 'tbl2' AS tbl, pid FROM tbl2 WHERe student_name = 'John Doe'UNIOn ALLSELECt student_name, 'tbl3' AS tbl, pid FROM tbl3 WHERe student_name = 'John Doe'...
然后在第二个调用中运行它,或者使用来使用PL /
pgSQL函数完全自动化它
EXECUTE。示例:
从表中选择一组动态列,并获取每个列的总和
该查询生成带有经过清理的标识符的 安全
代码,以防止SQL注入。(
oid::regclass这里的解释。)
还有更多相关答案。使用搜索。
顺便说一句,
LIKE在
student_name LIKE 'John Doe'没有意义。如果没有通配符,请使用
=。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)