I have two tables,
CREATE TABLE ActivityCodes (
ActivityCodeID INT NOT NULL PRIMARY KEY,
LocationID INT NOT NULL
);
and
CREATE TABLE LocationSettings (
LocationID INT NOT NULL PRIMARY KEY,
DefaultFooActivityCodeID INT,
FOREIGN KEY (DefaultFooActivityCodeID) REFERENCES ActivityCodes(ActivityCodeID)
);
with the foreign key relationship as indicated. Activity codes are valid only for the given LocationID
and DefaultFooActivityCodeID
in the LocationSettings
table should be an ActivityCodeID
where ActivityCodes.LocationID == LocationSettings.LocationID
. How can I enforce that in SQL? Can it be done with constraints or foreign keys? Is it possible at all?
Edit: Just to add some clarification, this what valid data in these table should look like:
ActivityCodes
ActivityCodeID | LocationID |
---|---|
1 | 123 |
2 | 123 |
3 | 456 |
4 | 456 |
LocationSettings
LocationID | DefaultFooActivityCodeID |
---|---|
123 | 1 |
456 | 4 |
A location can have multiple activity codes. The default activity code for a location must be an activity code for that location. @Charlieface I tried using a composite foreign key as suggested in the answer you linked but I get an error saying LocationID
on ActivityCodes
is neither unique nor a primary key (I'm using MS SQL Server).