views:

26

answers:

1

Say I have "Table A":

Id | Col A
1    Z
2    I
3    Null

...and n number of tables that have this format:

Id | A_FK | OtherInfo
1    1      "Some info"
2    2      "Some more info"
3    3      "Blah"

...where A_FK is a foreign key reference to the "Table A" Id.

So there is one "Table A", and n number of "Table B's". For these "B" tables, some of them can have any existing value for A_FK (no constraint required). Other "B" tables can only reference an A_FK value where the corresponding record does not have a Null value in Col A.

So my questions are:

  1. How would I write a constraint to take care of this (I imagine this is a pretty easy one, I just haven't ever had to write one and I'm feeling a bit lazy)?
  2. Does the constraint work in reverse? Say I've entered a record in a "B" table, and it's linked to Table A's Id = 1 (with the constraint in place for Table B). This is fine because Col A for Table A's 1 = "Z". Will there be an error if I try to change "Z" to Null at a later time?

Thanks in advance.

+2  A: 

In TableA, create a unique constraint on (ID, ColA), In the tables where "where the corresponding record does not have a Null value in Col A.", add ColA column, make sure it is NOT NULL, and have a FK constraint refer to that unique constraint in TableA.

This answers both your questions.

AlexKuznetsov
Thanks, seems kind of obvious now that you said it, hah.
Ocelot20