Thursday, August 26, 2010

Composite Foreign Keys

You learn something new every day...  Today I found a table that nobody could figure out - turns out it's sole purpose in life is to maintain foreign key relationships (via data) so the objects knew how to verify referential integrity before inserting.  After a little googling I found out that it is possible to have a composite foreign key.  Crazy I thought...  but it works.  If anyone has any (negative) experience in this area I would love to hear about it.

(Note I am now living with one foot in SQL Server land and the other in Oracle Land - hence the semicolons)

create table tmp1 (
  f1  char(1),
  f2  char(1),
  primary key (
    f1, f2)
);
 
create table tmp2 (
  f1  char(1),
  f2  char(1)
  , constraint FK_composite foreign key (f1, f2) references tmp1 (f1, f2)
);

insert into tmp1 (f1, f2) values ('1', '1');
insert into tmp1 (f1, f2) values ('2', '2');

-- succeeds
insert into tmp2 (f1, f2) values ('1', '1');
insert into tmp2 (f1, f2) values ('2', '2');

-- fails
insert into tmp2 (f1, f2) values ('1', '2');
insert into tmp2 (f1, f2) values ('2', '1');

select * from tmp1;
select * from tmp2;

drop table tmp2;
drop table tmp1;

No comments:

Post a Comment