Hello there,
I'm having problems coming up with an adequate restraint in SQL Server 2005. My problem involves the following tables:
Table PKTable
{
pk integer primary key,
property integer,
}
Table FKTable
{
pk integer primary key,
fk integer references PKTable(pk),
}
I really want to make it impossible for a record, fk_rec, to exist when the PKTable record it references has property = 5. The first thing I tried to do was create a schema bound view with the following query and create an unique index on the UniqueCol field.
SELECT 'True' AS UniqueCol, 'uh oh' AS DiffCol
FROM FKTable INNER JOIN
PKTable ON FKTable.fk = PKTable.pk
WHERE PKTable.property = 5
UNION
SELECT 'True' AS UniqueCol, 'default' AS DiffCol
So basically, the ('True', 'default') record will always exist in the view, and when someone attempts to insert a row into FKTable and the PKTable record it references has property = 5, I get a constraint violation because the first part of the union query above will return something. That was the idea anyway. But, SQL Server 2005 doesn't allow indices on views that involve a union. I then tried to create another view:
SELECT UniqueCol, DiffCol FROM TheViewAbove
Putting a unique index on UniqueCol fails in this case because you can't have indices on a view that reference another view. I knew it was a long shot. Any way to get around this?
Thanks!