如何从命令行删除PostgreSQL中的所有表?

我不想删除数据库本身,只想删除其中的所有表和所有数据。


当前回答

如果要删除的所有内容都属于同一用户,则可以使用:

drop owned by the_user;

这将删除用户拥有的所有内容。

这包括用户拥有(=创建)的物化视图、视图、序列、触发器、模式、函数、类型、聚合、运算符、域等(实际上是:所有)。

您必须用实际的用户名替换_user,目前没有选项删除“当前用户”的所有内容。即将推出的9.5版本将拥有current_user拥有的选项drop。

手册中的更多详细信息:http://www.postgresql.org/docs/current/static/sql-drop-owned.html

其他回答

将PSQL与\gexec一起使用

这是一个比迄今为止更全面的查询,因为它将处理特殊的表名。

SELECT FORMAT('DROP TABLE %I.%I.%I CASCADE;', table_catalog, table_schema, table_name)
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
  AND table_schema <> 'information_schema'
  AND table_schema NOT LIKE 'pg_%';

您可以预览要运行的命令,并且可以在psql中运行该查询后键入\gexec来执行该查询的输出。

注意:使用CASCADE将删除依赖于表的所有内容(如VIEW)

也许最简单的方法是:

删除数据库包含的表具有:删除数据库database_NAME;重新创建该数据库:创建数据库database_NAME;

在pgAdmin中使用此脚本:

DO $$
DECLARE 
    brow record;
BEGIN
    FOR brow IN (select 'drop table "' || tablename || '" cascade;' as table_name from pg_tables where schemaname = 'public') LOOP
        EXECUTE brow.table_name;
    END LOOP;
END; $$

您可以使用

DO $$ DECLARE
    r RECORD;
BEGIN
    -- if the schema you operate on is not "current", you will want to
    -- replace current_schema() in query with 'schematodeletetablesfrom'
    -- *and* update the generate 'DROP...' accordingly.
    FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = current_schema()) LOOP
        EXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(r.tablename) || ' CASCADE';
    END LOOP;
END $$;

IMO这比丢弃模式public要好,因为您不需要重新创建模式并恢复所有授权。

额外的好处是,这不需要外部脚本语言,也不需要将生成的SQL复制粘贴回解释器。

根据上面的Pablo,从一个特定的模式中删除案例:

select 'drop table "' || tablename || '" cascade;' 
from pg_tables where schemaname = 'public';