我有这样的查询来列出当前数据库中的表:
SELECT c.relname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind
IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND
pg_catalog.pg_table_is_visible(c.oid)
我试图使用上部SELECT来删除所有这些表,如子查询:
DROP TABLE IF EXISTS (SELECT c.relname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind
IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND
pg_catalog.pg_table_is_visible(c.oid)) as tname
但这不起作用。
如何编写一个查询,它将删除显示SELECT查询列出的所有表?
现在我使用DataReader循环查询结果并将表删除一个
但我认为这可能会“立刻”出现。
答案 0 :(得分:5)
你需要使用动态SQL,而这只能用于像PL / pgSQL这样的过程语言,如下所示:
do
$$
declare
stmt text;
table_rec record;
begin
for table_rec in (SELECT c.relname as tname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','')
AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
AND pg_catalog.pg_table_is_visible(c.oid))
loop
execute 'drop table '||table_rec.tname||' cascade';
end loop;
end;
$$
答案 1 :(得分:0)
您可以使用SELECT语句“生成” DROP语句。例如:
SELECT 'DROP TABLE "' + table_name + '"'
FROM information_schema.tables
WHERE table_name LIKE '[your_prefix_here]%'
(用您的条件和通配符替换'[your_prefix_here]%')