1. 程式人生 > >postgresql使用觸發器進行分表操作

postgresql使用觸發器進行分表操作

1.首先準備測試的父表:

2.建立子表:

create table info_2017(
check ( year = '2017' )       
) INHERITS (info);

create table info_2018(
check ( year = '2018' )       
) INHERITS (info);

3.建立各表索引

create index info_2017_index on info_2017(year);
create index info_2018_index on info_2018(year);

4.建立觸發器函式

CREATE OR REPLACE FUNCTION info_trigger()                      
RETURNS TRIGGER AS $$  
BEGIN  
    IF ( NEW.year = '2017') THEN  
        INSERT INTO info_2017 VALUES (NEW.*);  
    ELSIF (  NEW.year = '2018' ) THEN  
        INSERT INTO info_2018 VALUES (NEW.*);  
    ELSE  
        RAISE EXCEPTION 'Date out of range. Fix the tbl_partition_insert_trigger() function!';  
    END IF;  
    RETURN NULL;  
END;  
$$  
LANGUAGE plpgsql;



CREATE TRIGGER my_info_trigger
    BEFORE INSERT ON info
    FOR EACH ROW EXECUTE PROCEDURE info_trigger();


 

 

完成後的結果會根據插入語句的year欄位插入到分表,主表也會同時插入.據說會對效能有提升,還未測試;