If you have only a single thing to check, then astentex's answer will do you nicely. But if you have arbitrary constraints, especially spanning multiple tables, there is a different option which is more flexible.
It is based around a trick involving Indexed Views. I got this from an article by spaghettidba.
An indexed view is a view that is persisted to disk. We create it by creating a clustered index on the view. There are many limitations to it, crucially in our case that we can't use left/right/full join
, only inner
is allowed. It also must be schema-bound (you can't change the underlying columns), and must reference tables with two-part names.
Let us suppose that the opposite of your constraint is true: there are rows in BookShipment
for which the relevant Book
is not Approved
. How can we see such Books
in a view:
CREATE /* OR ALTER */ VIEW dbo.vwNonApprovedBooks
WITH SCHEMABINDING
AS
SELECT b.BookId
FROM dbo.BookShipment AS bs
JOIN dbo.Book AS b ON b.BookID = bs.BookID
WHERE b.Decision <> 'Approved';
GO
We could index this by creating a clustered index, DO NOT do this yet:
CREATE UNIQUE CLUSTERED INDEX CX_vwNonApprovedBooks ON dbo.vwNonApprovedBooks (BookId);
Now we will pull a little trick. If we want to stop any rows existing in this view, we need to force every inserted row to multiply out so that it fails the unique constraint.
Let us create a table for this:
CREATE TABLE dbo.DummyTwoRows (x bit NOT NULL PRIMARY KEY);
GO
INSERT dbo.DummyTwoRows VALUES (0),(1);
Now we can redefine the view like this:
CREATE /* OR ALTER */ VIEW dbo.vwNonApprovedBooks
WITH SCHEMABINDING
AS
SELECT 1 AS DummyOne
FROM dbo.BookShipment AS bs
JOIN dbo.Book AS b ON b.BookID = bs.BookID
CROSS JOIN dbo.DummyTwoRows
WHERE b.Decision <> 'Approved';
GO
CREATE UNIQUE CLUSTERED INDEX CX_vwNonApprovedBooks ON dbo.vwNonApprovedBooks (DummyOne);
And on any insert into BookShipment
with a Book
that is not Approved
, the unique constraint will fail.
SQL Server will maintain this view on inserts and updates, so that if a Book
is changed to not Approved
where it has BookShipment
, the constraint will fail the update also.
Note that this index takes up no space as there are never any rows in it.