Pergunta

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.

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top