— 一、现有函数
— 1、现有函数调用
select “ap”.”delete_analysis_backup”(‘ap’);
— 2、函数内容
CREATE OR REPLACE FUNCTION “ap”.”delete_analysis_backup”(“schema_name” varchar)
RETURNS “pg_catalog”.”void” AS $BODY$ DECLARE
row_tag VARCHAR ( 200 );
BEGIN– Created by Liu Jinhui
FOR row_tag IN (
SELECT TABLE_NAME
FROM
(
SELECT
tablename AS TABLE_NAME,
( regexp_match ( tablename, ‘analysis_[a-z,_]+_([0-9]{8,8})’ ) ) [ 1 ] AS table_backup_time
FROM
pg_tables
WHERE
schemaname = schema_name
AND tablename SIMILAR TO ‘analysis_[a-z,_]+_[0-9]{8,12}’
) A
WHERE
DATE_TRUNC( ‘day’, to_date( A.table_backup_time, ‘yyyyMMdd’ ) ) < DATE_TRUNC( ‘day’, now( ) + ‘-7 day’ )
)
LOOP
RAISE notice’表名为:%’,
row_tag;
EXECUTE concat ( ‘drop table ‘, SCHEMA_NAME, ‘.’, row_tag );
END LOOP;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
— 二、依赖项
— 要求:删除ods包含gyy的表,删除一个月
— 函数头:del_special_struct(schema_name,period_saved,remark)
— 调用:
select ods.del_special_struct(‘ap’,’1 days’,’删除以往的分析对象模型’)
select ods.del_special_struct(‘ods’,’31 days’,’删除一个月之前的gyy物理备份表’)
— 三、过程
— 要求:删除ods包含gyy的表,删除一个月
— 函数头:del_special_struct(schema_name,period_saved,remark)
— 调用:
select ods.del_special_struct(‘ap’,’1 days’,’删除以往的分析对象模型’);
select ods.del_special_struct(‘ods’,’31 days’,’删除一个月之前的gyy物理备份表’);
— 1、ap
CREATE OR REPLACE FUNCTION ods.del_special_struct(schema_name varchar,period_saved varchar,remark varchar)
RETURNS “pg_catalog”.”void” AS $BODY$ DECLARE
BEGIN
if schema_name = ‘ap’ then
EXECUTE select “ap”.”delete_analysis_backup”(‘ap’);
else
— gyy删除一个月前的表
end if;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
— 2、ods的管易云删除逻辑
— (1)查询出所有满足条件的表
select tablename,to_char(date(concat(’20’,split_part(tablename,’_20′,2))),’yyyymmdd’) as mon_day
from pg_tables
where schemaname = ‘ods’
and tablename SIMILAR TO ‘ods_trade_[a-z,_]+gyy_[2022][0-9,_]+’
and to_char(date(concat(’20’,split_part(tablename,’_20′,2))),’yyyymmdd’) < to_char(date_trunc(‘day’,now())+’-30 days’,’yyyymmdd’)
— (2)删除表
CREATE OR REPLACE FUNCTION ods.del_special_struct(schema_name varchar,period_saved varchar,remark varchar)
RETURNS “pg_catalog”.”void” AS $BODY$ DECLARE
DECLARE arrat_t varchar[];
DECLARE dt_split INTERVAL=’-‘ ||period_saved;
DECLARE tb_each VARCHAR;
DECLARE res VARCHAR;
BEGIN
if schema_name = ‘ap’ then
select ap.delete_analysis_backup(‘ap’) into res;
else
— gyy删除一个月前的表
— 如果存在分区表,则删除对应的物理表
select array(
select tablename from (
select tablename,to_char(date(concat(’20’,split_part(tablename,’_20′,2))),’yyyymmdd’) as mon_day
from pg_tables
where schemaname = ‘ods’
and tablename SIMILAR TO ‘ods_trade_[a-z,_]+gyy_[2022][0-9,_]+’
and to_char(date(concat(‘202′,split_part(tablename,’_202′,2))),’yyyymmdd’) < to_char(date_trunc(‘day’,now())+dt_split,’yyyymmdd’)
) all_table) into arrat_t;
foreach tb_each in array arrat_t
loop
EXECUTE format(‘DROP TABLE IF EXISTS %s.%s’, schema_name,tb_each);
end loop;
end if;
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
原文地址:http://www.cnblogs.com/liujinhui/p/16852394.html