PostgreSQL, drop tables with query

前端 未结 2 442
萌比男神i
萌比男神i 2021-01-15 01:12

I have such query to list tables in current database:

SELECT c.relname 
FROM pg_catalog.pg_class c 
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnames         


        
相关标签:
2条回答
  • 2021-01-15 01:45

    You need to use dynamic SQL for this, which in turn can only be used in a procedural language like PL/pgSQL, something like this:

    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;
    $$
    
    0 讨论(0)
  • 2021-01-15 02:03

    You can "generate" your DROP statement using a SELECT statement. For example:

    SELECT 'DROP TABLE "' + table_name + '"' 
    FROM information_schema.tables
    WHERE table_name LIKE '[your_prefix_here]%'
    

    (Replace '[your_prefix_here]%' with your conditions and wild cards)

    0 讨论(0)
提交回复
热议问题