I have a table that looks something like this:
CREATE TABLE A (
A_UNIQUE_ID int NOT NULL PRIMARY KEY,
A_OTHER_ID int NOT NULL,
A_CURRENT_FL bit NOT NULL )
and it has values similar to this
INSERT INTO TABLE A VALUES (1, 1, 0);
INSERT INTO TABLE A VALUES (2, 1, 0);
INSERT INTO TABLE A VALUES (3, 1, 1);
I want to create another table B like this
CREATE TABLE B (
B_UNIQUE_ID int NOT NULL PRIMARY KEY,
A_OTHER_ID int NOT NULL)
where B.A_OTHER_ID is constrained to a unique row in A. So B.A_OTHER_ID = A.A_OTHER_ID AND A.CURRENT_FL = 1. Is that possible with some type of check constraint setup? Examples are very much appreciated.
You can do it with some computed columns, but it doesn’t look very pretty:
This works:
This breaks the FK constraint:
The two computed columns in table A ensure that any row with
A_CURRENT_FL=1has that as a distinct value inOTHER_XREF. Other rows will haveNULLin that column. However, to apply aUNIQUEconstraint (the target for the foreign key), we need something that will be distinctly different for every row with aNULL, whilst being a well-known value for the row withA_CURRENT_FL=1. In this case, I made the well known value0.Finally, the foreign key constraint needs to match both of these columns, so we add a new computed column in table B with the well known value
0.Column names aren’t particularly good, but I’m sure you can come up with some.
Note, also, that by the above, we’ve also implemented another constraint that you didn’t mention, but that also may be important – there can’t be two rows now in table A that both have
A_CURRENT_FLset to 1, for the sameA_OTHER_IDvalue. This also generates an error: