简体   繁体   中英

Create primary key for table with period (Temporal Validity) in Oracle SQL

I have a question regarding to primary key for Oracle Table with Period.

I have created two tables like following:

create table el_temporal_try( -- Parent Table
    id number(10) not null,
    ColumnA varchar(10),
    constraint el_temporal_try_pk primary key (id),
    period for valid_period
);
create table el_temporal_try_son( -- Son Table
    id number(10) not null,
    ColumnA varchar(10),
    parent_id number(10),
    constraint el_temporal_try_FY foreign key (parent_id) references el_temporal_try(id),
    period for valid_period
);

This script gone through successfully. However I have problem with inserting data:

I have executed following two insert statements into the parent table:

1st: statement

insert into el_temporal_try 
(id, columnA,valid_period_start, valid_period_end)
values
(1,'A',sysdate - 10, sysdate - 9);

Result:

1 row inserted.

2nd: statement

insert into el_temporal_try 
(id, columnA,valid_period_start, valid_period_end)
values
(1,'B',sysdate - 8, sysdate - 7);

Result

ORA-00001: unique constraint (PBSVW.EL_TEMPORAL_TRY_PK) violated

I understand it is because of the "ID" column. However, my issues because this two rows are for a different period, should it be allowed?

I was intended to use this period for feature to capture the change history of a record as an alternative to flashback. However, does it means that I should not use primary key at this situation?

Thanks in advance!

The problem is related to the id column like you said. it's not possible to add the registry because the primary key is unique, then your second insert statement references the same ID from the first. You need to change the ID always you insert a line.

On Oracle 12c, you can use the identity like this link. https://www.oracletutorial.com/oracle-basics/oracle-identity-column/

in another version, you can use sequence and trigger to do this. https://chartio.com/resources/tutorials/how-to-define-an-auto-increment-primary-key-in-oracle/

Thanks for everyone's help on this. This most likely means I cannot use Primary Key/Foreign Key to maintain the referential integrity between the parent and son for my situation within a particular timestamp, but I have to go for something else.

Thanks a lot!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM