views:

59

answers:

3

It's easier with an example. I have two tables: Books and Chapters. Both have Title and Id columns. Chapters also has a Book column which is a foreign key to Books.Id. Books.Title is unique (I don't want two books with the same title).

Now my problem is defining Chapter.Title uniqueness. I want it to be unique as long as Books.Id is the same. So that one book may not have two chapters with the same title but two different books may have the same title in a chapter.

Is this possible on SQL Server 2008? How?

+3  A: 

Create a UNIQUE INDEX on Chapters using columns BookID and Title (indexes may include several columns, not just one)

devio
+2  A: 

So within Chapter, it is the combination of Book and Title that must be unique. Simply create a UNIQUE index spanning those columns, and you're done.

By the way, I can't help but think that

(I don't want two books with the same title)

is going to come back and bite you, if you're actually talking about real-world books. If this is just an example, then no worries.

AakashM
upvoted for the advice that the forced uniqueness of a book name will come back to bite you!
Raj More
+4  A: 

UNIQUE CONSTRAINT or UNIQUE index. Either will do.

ALTER TABLE dbo.MyTable WITH CHECK ADD
    CONSTRAINT UQ_MyTable_BookTitle UNIQUE (BookID, Title)

or

CREATE UNIQUE INDEX IXU_MyTable_BookTitle ON dbo.MyTable (BookID, Title)
gbn