如何从命令行删除PostgreSQL中的所有表?
我不想删除数据库本身,只想删除其中的所有表和所有数据。
如何从命令行删除PostgreSQL中的所有表?
我不想删除数据库本身,只想删除其中的所有表和所有数据。
当前回答
如果要删除数据(而不是删除表):
-- Truncate tables and restart sequnces
SELECT 'TRUNCATE TABLE "' || table_schema || '"."' || table_name || '" RESTART IDENTITY CASCADE;'
FROM information_schema.tables
WHERE table_catalog = '<database>' AND table_schema = '<schema>';
或者,如果您想要删除表,可以使用以下sql:
-- For tables
SELECT 'DROP TABLE "' || table_schema || '"."' || table_name || '" CASCADE;'
FROM information_schema.tables
WHERE table_catalog = '<database>' AND table_schema = '<schema>';
-- For sequences
SELECT 'DROP SEQUENCE d_a_seq "' || sequence_schema || '"."' || sequence_name || '";'
FROM information_schema.sequences
WHERE sequence_catalog = '<database>' AND sequence_schema = '<schema>';
其他回答
在Windows批处理文件中:
@echo off
FOR /f "tokens=2 delims=|" %%G IN ('psql --host localhost --username postgres --command="\dt" YOUR_TABLE_NAME') DO (
psql --host localhost --username postgres --command="DROP table if exists %%G cascade" sfkb
echo table %%G dropped
)
将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)
drop schema public cascade;
应该会成功。
如果要删除的所有内容都属于同一用户,则可以使用:
drop owned by the_user;
这将删除用户拥有的所有内容。
这包括用户拥有(=创建)的物化视图、视图、序列、触发器、模式、函数、类型、聚合、运算符、域等(实际上是:所有)。
您必须用实际的用户名替换_user,目前没有选项删除“当前用户”的所有内容。即将推出的9.5版本将拥有current_user拥有的选项drop。
手册中的更多详细信息:http://www.postgresql.org/docs/current/static/sql-drop-owned.html
嗯,因为我喜欢从命令行工作。。。
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。