Oracle FAQ | Your Portal to the Oracle Knowledge Grid |
![]() |
![]() |
Home -> Community -> Usenet -> c.d.o.server -> Re: Complex Primary Key Validation
Brian Tkatch <SPAMBLOCK.Maxwell_Smart_at_ThePentagon.com.SPAMBLOCK> wrote in
message news:3c4c68d8.1165610016_at_news.alt.net...
> >
> You could easily use a TRIGGER to fire ON INSERT OR UPDATE to throw
> an EXCEPTION when the data fails your business rule.
>
Not so easy.
First, you have to get round the mutating table problem i.e. you cannot
access data in the table for which the trigger is fired. This often means
using a package and pl/sql table which has implications for scalability and
performance.
Second, you have to prevent the insertion of rows that would violate the
constraint in another session which normally requires you to lock a parent
row or something similar, which serialises inserts against a particular id
again giving the potential for performance/locking issues.
Without this, the following scenario can occur:
Session A Session Binsert row
insert row that violates constraint in conjunction with A check data cannot see uncommited row returns ok commit commit
The result is corrupt data
I have attached outline code to do the job, though it needs tidying up with comments, error handling etc. It also assumes that the number of rows per id is small, as it iterates through them.
An alternative, if the dates are precise only to the day, is to have a table of Id, EffectiveDate populated by trigger expanding all intermediate days. This has a primary key on Id, EffectiveDate and prevents overlapping ranges being entered.
create table FredParent( Id number not null ); insert into FredParent values(1);
create table fred
( id number not null
, fromdate date not null
, todate date not null
);
alter table fred
add constraint fred_pk
primary key ( id, fromdate, todate );
![]() |
![]() |