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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.