views:

86

answers:

2

This comes up a lot for me. In SQL Server 2008, I have 3 tables. 2 with unique keys and 1 which is a mapping between them. Example:

People    Events   Schedule
------    ------   --------
PersonId  EventId  ScheduleId
Name      Place    PersonId
                   EventId
                   Rsvp

ScheduleId isn't needed if I make a composite key. I know how to make a composite key like this

ALTER TABLE Schedule ADD CONSTRAINT CK_Schedule_PersonId_EventId
UNIQUE NONCLUSTERED (PersonId, EventId)

but I don't know how to make one that also maps correctly to the foreign keys. How can I do this? Also, if I'm wrong and the ScheduleId way is preferred, please say why.

+1  A: 

I will not use composite key in this case due to scalability of database. Suppose if you have 6 foreign keys in your table(Schedule) and ScheduleId is being used in some other tables than I will not use all the 6 foreign keys in upcoming tables. I will try to use ScheduleId as my foreign key.

Shantanu Gupta
+3  A: 

ScheduleId is usually preferred for ORMs and it gives an absolutely unique and unchangeable primary key that represents a record. Primary keys should not change. Also it makes dealing with records a bit more easy. You just need to give the id for an update or delete instead of passing in a composite identifier.

You can create the foreign key when you are doing the definition for Schedule:

PersonId int FOREIGN KEY REFERENCES People(PersonId)

or

CONSTRAINT fk_PersonId FOREIGN KEY (PersonId) REFERENCES People(PersonId)

or if you are altering an existing table

ALTER TABLE Schedule ADD CONSTRAINT fk_PersonId
FOREIGN KEY (PersonId) REFERENCES People(PersonId)

And I'll mention that if you do make a composite fk then you should make it the primary key to ensure that it is not only unique but not null.

CONSTRAINT pk_Person_Event PRIMARY KEY (PersonId, EventId)
Arthur Thomas
Do you think I should use a single primary key with a constraint to prevent duplicate pairing, or should I leave that for my business logic to enforce?
Dinah
+1: The `scheduleid` is also used by lazy programmer who simply don't want the hassle of referencing 2+ columns for a primary key. Also, a composite key doesn't have to be the primary key, but it is the case for this example.
OMG Ponies
@Dinah: A single column primary key and accompanying unique constraints is overcomplicating the situation. If there isn't a use for the single column primary key, make the composite the primary key.
OMG Ponies
@Dinah yes, I would really recommend a single 'surrogate' key as the primary key. And definitely put a constraint on the natural key. Unique and Not null would be good from what I can see. Databases should maintain data integrity and not rely on business code. Just think of multiple apps using the DB and one of them not doing its job correctly.
Arthur Thomas