按月分区触发器函数编写,自动创建分区表

CREATE OR REPLACE FUNCTION trigger_function_test_yum() RETURNS trigger AS $BODY$ DECLARE str_time varchar; str_sub_tablename varchar; str_sql_cmd varchar; BEGIN IF TG_OP <> 'INSERT' OR TG_TABLE_NAME <>'test_yum' OR TG_WHEN <> 'BEFORE' THEN RETURN NULL; END IF; --Generate Table Name str_time = date_part('year',NEW.A)::varchar || '_' || CASE WHEN date_part('month',NEW.A) <10 THEN '0' ELSE '' END ||date_part('month',NEW.A)::varchar; str_sub_tablename = 'test_yum_' || str_time; --Check if table not created select * from pg_tables where schemaname = 'public' and tablename=str_sub_tablename into str_sql_cmd; IF NOT FOUND THEN --Create table Cmd str_sql_cmd = 'CREATE TABLE '||str_sub_tablename|| ' (CONSTRAINT chk_'|| str_sub_tablename|| ' CHECK(date_part(''year''::text,A) = '|| date_part('year',NEW.A)::varchar|| ' AND date_part(''month''::text,A) = '|| date_part('month',NEW.A)::varchar|| ' )) INHERITS (test_yum) TABLESPACE ts_yum_global;'; EXECUTE str_sql_cmd; END IF; --insert Data str_sql_cmd = 'INSERT INTO '||str_sub_tablename||' VALUES($1,$2);'; EXECUTE str_sql_cmd USING NEW.A,NEW.B; --return null because main table does not really contain data RETURN NULL; END; $BODY$ LANGUAGE plpgsql VOLATILE COST 100; ALTER FUNCTION trigger_function_test_yum() OWNER TO postgres;

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...