在我的数据库中有113个表,
drop
名为ilike '%gtab%'
答案 0 :(得分:2)
这将创建删除所述表的语句,不匹配该模式的其他对象。也没有系统表。
SELECT 'DROP TABLE ' || c.oid::regclass || ';'
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace -- to restrict to a schema
WHERE c.relkind = 'r' -- only tables
AND c.relname ILIKE '%gtab%' -- pattern for table names
AND n.nspname = 'public' -- restrict to a schema
ORDER BY 1;
转换为regclass
会根据需要自动转义并对表名进行模式限定,并且可以安全地防止SQL注入。详细说明:
对于许多表,单个集成语句将更快:
SELECT 'DROP TABLE ' || string_agg(c.oid::regclass::text, ', ') || ';'
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
AND c.relname ILIKE '%gtab%'
AND n.nspname = 'public'
ORDER BY 1;
结果:
DROP TABLE tbl1, tbl2, schema1.tbl3;
相关答案:
答案 1 :(得分:1)
获取名称为gtab
select relname from pg_class where relname ilike '%gtab%' and relname not ilike
'%seq%' and relname not ilike '%pkey%' and relname not ilike '%idx%'
如果您想获得drop query
,只需使用COPY
函数导出到.CSV文件,然后从导出的csv文件中复制所有drop
查询和execute
pgScript
copy (select 'drop table ' || relname || ' cascade;' from pg_class where relname
ilike '%gtab%' and relname not ilike '%seq%'and relname not ilike '%pkey%' and
relname not ilike '%idx%' ) to'D:\DropScript.csv' with csv header
答案 2 :(得分:0)
您可以在loop
:
t=# begin;
BEGIN
t=# do
t-# $$
t$# declare r record;
t$# begin
t$# for r in (select schemaname||'.'||tablename tn from pg_tables where tablename like '%gtab%') loop
t$# raise info '%','dropping '||r.tn;
t$# execute CONCAT('DROP TABLE '||r.tn);
t$# end loop;
t$# end;
t$# $$
t-# ;
INFO: dropping public.agtab
INFO: dropping public.bgtabb
DO
t=# rollback;
ROLLBACK