Created
November 1, 2020 10:57
-
-
Save Calcifer777/b2a2b5890151d6aa5d14978f1c6561e0 to your computer and use it in GitHub Desktop.
postgres scd2 (slow changing dimension) trigger implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
create table records ( | |
record_id int, | |
record_name varchar(100), | |
record_value int, | |
date_start timestamp default now(), | |
date_end timestamp default null, | |
primary key(record_id, record_name, date_start) | |
); | |
insert into records (record_id, record_name, record_value) | |
values | |
(1, 'r1', 30), | |
(2, 'r2', 42) | |
; | |
select * from records; | |
CREATE OR REPLACE function public.scd2() | |
returns trigger | |
AS $BODY$ | |
BEGIN | |
update records | |
set date_end = now() | |
where record_name=new.record_name | |
and date_end is null; | |
return new; | |
END; | |
$BODY$ | |
LANGUAGE plpgsql; | |
CREATE TRIGGER example_trigger before INSERT ON records | |
FOR EACH ROW EXECUTE PROCEDURE scd2(); | |
insert into records (record_id, record_name, record_value) | |
values | |
(1, 'r1', 45) | |
; | |
select * from records; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment