How to drop multiple tables in PostgreSQL using a wildcard

前端 未结 7 2000
闹比i
闹比i 2020-12-13 05:39

When working with partitions, there is often a need to delete all partitions at once.

However

DROP TABLE tablename*

Does not work.

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-13 05:54

    I've always felt way more comfortable creating a sql script I can review and test before I run it than relying on getting the plpgsql just right so it doesn't blow away my database. Something simple in bash that selects the tablenames from the catalog, then creates the drop statements for me. So for 8.4.x you'd get this basic query:

    SELECT 'drop table '||n.nspname ||'.'|| c.relname||';' as "Name" 
    FROM pg_catalog.pg_class c
         LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
    WHERE c.relkind IN ('r','v','S','')
         AND n.nspname <> 'pg_catalog'
         AND n.nspname <> 'information_schema'
         AND n.nspname !~ '^pg_toast'
    AND pg_catalog.pg_table_is_visible(c.oid);
    

    Which you can add a where clause to. (where c.relname ilike 'bubba%')

    Output looks like this:

             Name          
    -----------------------
     drop table public.a1;
     drop table public.a2;
    

    So, save that to a .sql file and run it with psql -f filename.sql

提交回复
热议问题