如果您有两张桌子,那就让我们说Doors and House。
桌子通过外键(门到门)连接。限制是一个房子有2到10个门。
在数据级别强制执行此操作的最佳方法是什么?
答案 0 :(得分:1)
create table houses (id int primary key)
create table doors (
id int primary key,
house_id int references houses(id)
)
create trigger doorsCondition on doors
instead of insert
AS
declare @max int, @min int
select @max = max(i), @min = min(i) from (
select count(1) i from (
select house_id from doors where house_id = ANY (select house_id from inserted)
union all
select house_id from inserted) subquery
group by house_id) subQuery2
if (@max <= 10 and @min >= 2)
insert into doors select * from inserted
else
print 'The insert violates business constraint'
和相应的删除触发器。您可以将它们合并为一个,但在这个简单的场景中,我不确定它是否值得考虑所有事情。