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

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


当前回答

嗯,因为我喜欢从命令行工作。。。

psql -U <user> -d <mydb> -c '\dt' | cut -d ' ' -f 4 | sed -e "s/^/drop table if exists /" | sed -e "s/$/;/"

-c'\dt'将调用list tables命令。

               List of relations
 Schema |       Name        | Type  |  Owner
--------+-------------------+-------+----------
 public | _d_psidxddlparm   | table | djuser
 public | _d_psindexdefn    | table | djuser

现在剪切-d“”-f 4,通过管道将其输出抓取第4个字段(当使用空格作为分隔符时),即表。

然后,sed被用于给一个drop表加前缀,并在后面加后缀;命令分隔符。

|egrep“_d_”-再将其转换为grep,这样您就可以更有选择地删除哪些表。

drop table if exists _d_psidxddlparm;
drop table if exists _d_psindexdefn;

注意:如前所述,这将为\dt命令输出的列标题和末尾的总行生成伪行。我会用grepping来避免,但你可以用head和tail。

其他回答

也许最简单的方法是:

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

我通过关注视图增强了jamie的bash方法,因为他只关注默认的表类型“base table”。

以下bash代码首先删除视图,然后删除所有其余视图

#!/usr/bin/env bash

PGDB="yourDB"
# By exporting user & pass your dont need to interactively type them on execution
export PGUSER="PGusername"
export PGPASSWORD="PGpassword"

VIEWS=`psql -d $PGDB -t --command "SELECT string_agg(table_name, ',') FROM information_schema.tables WHERE table_schema='public' AND table_type='VIEW'"`
BASETBLS=`psql -d $PGDB -t --command "SELECT string_agg(table_name, ',') FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE'"`

echo Dropping views:${VIEWS}
psql $PGDB --command "DROP VIEW IF EXISTS ${VIEWS} CASCADE"
echo Dropping tables:${BASETBLS}
psql $PGDB --command "DROP TABLE IF EXISTS ${BASETBLS} CASCADE"

你需要删除表和序列,这是对我有用的

psql -qAtX -c "select 'DROP TABLE IF EXISTS ' || quote_ident(table_schema) || '.' || quote_ident(table_name) || ' CASCADE;' FROM information_schema.tables where table_type = 'BASE TABLE' and not table_schema ~ '^(information_schema|pg_.*)$'" | psql -qAtX
psql -qAtX -c "select 'DROP SEQUENCE IF EXISTS ' || quote_ident(relname) || ' CASCADE;' from pg_statio_user_sequences;" | psql -qAtX

在运行该命令之前,可能需要sudo/su到postgres用户或(导出连接详细信息PGHOST、PGPORT、PGUSER和PGPASSWORD),然后导出PGDATABASE=yourdatabase

以下步骤可能会有所帮助(对于linux用户):

首先,通过以下命令输入postgres命令提示符:sudo-u postgres psql通过以下命令输入数据库(我的数据库名为:maoss):\c猫现在输入删除所有表格的命令:DROP SCHEMA公共级联;CREATE SCHEMA公共;向公众授予所有计划;向公众公开所有计划;现在通过以下命令退出psql:\问

如果您无论如何都想对所有表进行核处理,可以通过将所有表放在一个语句中来省去诸如CASCADE之类的细节。这也使执行速度更快。

SELECT 'TRUNCATE TABLE ' || string_agg('"' || tablename || '"', ', ') || ';' 
FROM pg_tables WHERE schemaname = 'public';

直接执行:

DO $$
DECLARE tablenames text;
BEGIN    
    tablenames := string_agg('"' || tablename || '"', ', ') 
        FROM pg_tables WHERE schemaname = 'public';
    EXECUTE 'TRUNCATE TABLE ' || tablenames;
END; $$

如果适用,用DROP替换TRUNCATE。