暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

PG 工具函数

原创 岳麓丹枫 2023-05-03
214

批量清空指定用户的表

CREATE OR REPLACE FUNCTION f_truncate_tables(_username text) RETURNS void LANGUAGE plpgsql AS $func$ BEGIN EXECUTE (SELECT 'TRUNCATE TABLE ' || string_agg(format('%I.%I', schemaname, tablename), ', ') || ' CASCADE' FROM pg_tables WHERE tableowner = _username AND schemaname = 'public' ); END $func$;
复制
  • 实操
[postgres@node01 ~]$ psql -d test psql (14.5) Type "help" for help. test=# create table t1(id int); CREATE TABLE test=# create table t2(id int); CREATE TABLE test=# insert into t1 values(1),(2); INSERT 0 2 test=# insert into t2 values(1),(2),(3); INSERT 0 3 test=# select * from t1; id ---- 1 2 (2 rows) test=# select * from t2; id ---- 1 2 3 (3 rows) test=# CREATE OR REPLACE FUNCTION f_truncate_tables(_username text) test-# RETURNS void test-# LANGUAGE plpgsql AS test-# $func$ test$# BEGIN test$# EXECUTE test$# (SELECT 'TRUNCATE TABLE ' test$# || string_agg(format('%I.%I', schemaname, tablename), ', ') test$# || ' CASCADE' test$# FROM pg_tables test$# WHERE tableowner = _username test$# AND schemaname = 'public' test$# ); test$# END test$# $func$; CREATE FUNCTION test=# test=# select f_truncate_tables('postgres'); f_truncate_tables ------------------- (1 row) test=# \dt List of relations Schema | Name | Type | Owner --------+------+-------+---------- public | t1 | table | postgres public | t2 | table | postgres (2 rows) test=# select * from t1; id ---- (0 rows) test=# select * from t2; id ---- (0 rows)
复制

参考:
https://stackoverflow.com/questions/2829158/truncating-all-tables-in-a-postgres-database/12082038#12082038

最后修改时间:2023-05-03 15:35:31
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论