Skip to content
Advertisement

Add FK / Constraint to subsection of table

Setup

Here’s two simplified* tables that illustrate the problem I have
*The actual tables are built such that I can’t really refactor the columns or split them apart easily

Table: CodeValues

Where CodeSet + CodeValue are a composite primary key

Table: Address

Where AddressID is the primary key


What is the appropriate DB constraint to add to Address.State?

It should always be a value that is present in CodeValues Where CodeSet = 'States', but I don’t believe I can create a Foreign Key that is part of a Composite Primary Key

Should it just be a check constraint based on a query like this?

My concern is that db design tools won’t really recognize the full impact of this constraint against, when it really is a FK, but just against a subsection of the table.

Advertisement

Answer

One method uses a little bit more storage, but it accomplishes what you want:

The ? is for the length of the varchar() column in the codevalues table.

Happily, you don’t need triggers or user-defined functions to accomplish this.

Unhappily, you need to persist the codeset in each row, so that eats up a wee bit of space in the table.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement