[英]Delete all Contents from postgreSQL
i have a Database with a lots of Tables. 我有一个包含大量表格的数据库。
is there a way to clear the contents of the Tables without to do that for each Table! 有没有办法清除表的内容,而不是为每个表做到这一点! i mean a way to iterate the Database Tables List and delete its contents. 我的意思是迭代数据库表列表并删除其内容的方法。
Thanx for your help. Thanx的帮助。
A simple database function which iterates over all tables in a schema and clear his content. 一个简单的数据库函数,它迭代模式中的所有表并清除其内容。 WARNING: this function clear all tables without asking if you are sure :) Use with caution! 警告:此功能清除所有表格而不询问您是否确定:)请谨慎使用! No warranty! 没有保修!
CREATE OR REPLACE FUNCTION clear_tables_in_schema(_schemaname TEXT)RETURNS VOID AS
$$
DECLARE _tablename TEXT;
BEGIN
FOR _tablename IN SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = _schemaname LOOP
RAISE INFO 'Clearing table %.%', _schemaname, _tablename ;
EXECUTE format('TRUNCATE %I.%I CASCADE;', _schemaname, _tablename);
END LOOP;
IF NOT FOUND THEN
RAISE WARNING 'Schema % does not exist', _schemaname;
END IF;
END;
$$
LANGUAGE plpgsql;
-- Usage:
SELECT clear_tables_in_schema('your_schema');
Something like: 就像是:
#!/bin/bash
# Save the schema
pg_dump -U user --format plain --schema-only --file db_schema.sql dbname
com="psql -h host -U user -d dbname"
$com <<EOF
DROP TABLE foo;
DROP TABLE bar;
DROP TABLE baz;
# ... more tables here ...
EOF
# Recreate all tables
$com < db_schema.sql
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.