Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a foreign key referencing a column in a view in SQL Server?

In SQL Server 2008 and given

TableA(A_ID, A_Data) TableB(B_ID, B_Data) ViewC(A_or_B_ID, A_or_B_Data) 

is it possible to define TableZ(A_or_B_ID, Z_Data) such that Z.A_or_B_ID column is constrained to the values found in ViewC? Can this be done with a foreign key against the view?

like image 638
marc Avatar asked Jan 15 '09 15:01

marc


People also ask

Can you have a foreign key on a view?

In the strict sense of the word, no you cannot set foreign keys on views.

Can a foreign key reference a column in the same table?

FOREIGN KEY constraints can reference another column in the same table, and is referred to as a self-reference. A FOREIGN KEY constraint specified at the column level can list only one reference column. This column must have the same data type as the column on which the constraint is defined.

Can a foreign key reference a column that is not a primary key?

A foreign key can refer to either a unique or a primary key of the parent table. If the foreign key refers to a non-primary unique key, you must specify the column names of the key explicitly.


2 Answers

You can't reference a view in a foreign key.

like image 78
Brian Fisher Avatar answered Sep 22 '22 12:09

Brian Fisher


In older SQL Server editions foreign keys were possible only through triggers. You can mimic a custom foreign key by creating an Insert trigger which checks whether the inserted value appears in one of the relevant tables as well.

like image 38
lorin_f Avatar answered Sep 23 '22 12:09

lorin_f