How do I specify a column to be unique in the scope of a relationship in SQL Server 2008?

梦想与她 提交于 2019-12-13 03:25:59

问题


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?


回答1:


UNIQUE CONSTRAINT or UNIQUE index. Either one 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)



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/1026441/how-do-i-specify-a-column-to-be-unique-in-the-scope-of-a-relationship-in-sql-ser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!