如何从命令行删除PostgreSQL中的所有表?
我不想删除数据库本身,只想删除其中的所有表和所有数据。
如何从命令行删除PostgreSQL中的所有表?
我不想删除数据库本身,只想删除其中的所有表和所有数据。
当前回答
drop schema public cascade;
应该会成功。
其他回答
我通过关注视图增强了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"
继Pablo和LenW之后,这里有一个单行程序,它既准备又执行:
psql-U$PGUSER$PGDB-t-c“从pg_tables中选择'drop table\”'||tablename||'\“cascade;',其中schemaname='public'”|psql-U$PGUSER$PGDB
注意:设置$PGUSER和$PGDB或将其替换为所需的值
您可以使用string_agg函数创建逗号分隔的列表,非常适合DROP TABLE。从bash脚本:
#!/bin/bash
TABLES=`psql $PGDB -t --command "SELECT string_agg(table_name, ',') FROM information_schema.tables WHERE table_schema='public'"`
echo Dropping tables:${TABLES}
psql $PGDB --command "DROP TABLE IF EXISTS ${TABLES} CASCADE"
您可以使用
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';