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 plpg
sql VOLATILE COST 100; ALTER FUNCTION trigger_function_test_yum() OWNER TO postgres;