检查组功能的约束?

时间:2013-05-27 18:09:22

标签: sql constraints exists

我需要一个SQL约束(使用SQLDeveloper)来检查对于特定的account_id,只存在一个或者不存在regular_id,例如附加的数据,包含'6'的单元格是不应该被允许的,即使它是一个不同的价值。

AccountID    RegularID     OpenID
 1            5             null
 1            null          10
 1            null          11
 1            6                             <-- Forbidden

1 个答案:

答案 0 :(得分:3)

最好的方法是使用触发器

  Create trigger trig_NoSingleRegId 
  On MyTable For Insert, Update
  As

        if Exists(Select * From MyTable t
                   Where AccountId In (Select AcountId From inserted)
                   Group By AccountId   
                   Having Count(Distinct regularId) > 1)     
        Begin
            RollBack Transaction
            Raiserror('Cannot have more than one RegularId per AccountId', 16, 1)
        End    

注意:Where子句仅用于执行,仅将触发器限制为仅由触发更新或插入插入或更新的那些accountId。

或者您也可以使用join来完成相同的限制。

  Create trigger trig_NoSingleRegId 
  On MyTable For Insert, Update
  As

        if Exists(Select * From MyTable t
                      join inserted I
                           on i.AccountId = t.AccountId
                   Group By t.AccountId   
                   Having Count(Distinct t.regularId) > 1)     
        Begin
            RollBack Transaction
            Raiserror('Cannot have more than one RegularId per AccountId', 16, 1)
        End