I have very simple database in SQL Server, with these three tables:
Theater
(ID, is3D,
othervalues...)Show
(ID, Theater_ID, Movie_ID, date, time,
othervalues...)Movie
(ID, is3D,
othervalues...)
I would like to ensure that 3D movies can be only played in 3D theaters. 2D movies only in 2D theaters, and doing it ONLY BY foreign keys (no triggers etc.).
To do this through foreign keys alone you need to add an
is3D
column toShow
as well and a couple of logically redundantUNIQUE
constraints.An indexed view can also be used to enforce this declaratively without requiring the additional column or unique constraints as below.
The underlying query should always return no rows if the rule is satisfied. If any row is returned then the cross join on
dbo.TwoRows
will multiply it out causing a unique constraint violation and preventing the situation.