2

如果你有两张桌子,我们就说 Doors 和 House。

这些表通过外键(门到户)连接。限制条件是一所房子有 2 到 10 扇门。

在数据级别上执行此操作的最佳方法是什么?

4

1 回答 1

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'

以及相应的删除触发器。您可能可以将它们合并为一个,但在这个简单的场景中,考虑到所有因素,我不确定这是否值得。

于 2013-10-14T11:56:27.600 回答