Proper foreign keys for MS SQL Server 2005 without UNIQUE constraints? -
i have 2 tables (ms sql server 2005) existing application (no db alterations other indexes, etc allowed).
the 2 tables are:
activitydetails (primary table) activitydetailkey (primary key) subactivities (child table) activitydetailkey (refers activitydetails)
now, there no contraints on subactivities
activitydetailkey
. basically, each activitydetail
row, there can many subactivities
rows , there nothing stopping user deleting activitydetails
row , leaving subactivities
orphaned.
there supposed "soft locks" in application prevent isn't working , wanted put better integrity in db layer too.
but can't seem add foreign key because subactivities
's activitydetailkey
column isn't unique.
how can prevent people deleting activitydetails
rows if there children present?
thanks
edit
i apologize complexity. subactivities
table named tedetailsubactivities
. changed in question easier read.
but anyway, here gist of complete schema both tables.
https://gist.github.com/840479
i appreciate help.
it sounds you're trying set foreign key wrong way around - if there multiple rows in subactivities same activitydetailkey value, , these references primary key in activitydetails, following should work (based on posted schema, , tested):
alter table tedetailsubactivities add constraint fk_tedetailsubactivities_activitydetails foreign key (activitydetailkey) references dbo.activitydetails (activitydetailkey)
previous version, based on table names in post:
alter table subactivities add constraint fk_subactivities_activitydetails foreign key (activitydetailkey) references activitydetails (activitydetailkey)
there's no uniqueness requirement on activitydetailkey column in subactivities.
as-is, that'll stop deletion of rows activitydetails if there rows in subactivities reference them. if, on other hand, want application able continue deletes, avoid leaving orphaned rows in subactivities, add on delete cascade
after final closing bracket above.
the above works based on following table definitions. if doesn't work in database, need out posting either actual table definitions database, or "close enough" mimic you're seeing:
create table activitydetails ( activitydetailkey int not null primary key ) go create table subactivities ( activitydetailkey int not null ) go
sigh. if you're going insist on using ssms designers:
- right click on subactivities, choose "design".
- press "relationships" toolbar button
- press "add"
- press "..." against "tables , columns specification" property
- in "primary key table" drop down, choose "activitydetails"
- in grid below, choose activitydetailkey on both sides
- press "ok", "close", "save" toolbar button, , (if necessary) "yes" save warning
- close designer.
Comments
Post a Comment