开发者

Foreign Key constraints in SQL Server

I have a database scheme with versioning data rows, e.g. Table Person has the columns

id (int, PK)
name (String)
current (Bool)
firstid (int)

Current is 0 for previous data, 1 for the latest entry. All rows for the same entity have the sa开发者_开发知识库me FirstID, which points to the first ID of the set.

Referencing table: Adress with the same principle:

id (int, PK)
street (String)
person_id (int)
current (Bool)
firstid (int)

Person_id points to patient.firstid. So firstid is never unique, only if current=1

My problem is: I would like to add referential integrity to my tables, but this only works, if the referenced column (patient.firstid) is unique...


You should look at refactoring your table structure. But to keep within the current structure, add a self-referencing foreign key to person

firstid references person(id)

Then, reference the "base person" from the address table

address.person_id references person(id) -- which should ONLY store a link to the first id


A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table. A FOREIGN KEY constraint can contain null values; however, if any column of a composite FOREIGN KEY constraint contains null values, then verification of the FOREIGN KEY constraint will be skipped.

Data from two related tables can be combined even if no PRIMARY KEY or FOREIGN KEY constraints are defined between the tables, but a foreign key relationship between two tables indicates that the two tables have been optimized to be combined in a query that uses the keys as its criteria.

reference http://msdn.microsoft.com/en-us/library/aa933117(v=sql.80).aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜