Tobias Schittkowski
Tobias Schittkowski

Reputation: 2251

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 same 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...

Upvotes: 1

Views: 387

Answers (2)

zudokod
zudokod

Reputation: 4094

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

Upvotes: 0

RichardTheKiwi
RichardTheKiwi

Reputation: 107686

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

Upvotes: 1

Related Questions