2013-05-27 21 views
1

我需要一个SQL约束(使用SQLDeveloper)来检查一个特定的account_id,只有ONE或NO regular_id存在,比如附加的数据,包含'6'的单元格是不应该被允许的,尽管它是一个不同的值。检查组功能的约束?

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

回答

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子句仅用于性能,限制触发仅由触发更新插入或更新或插入那些accountIds。

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

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   
+0

即使尝试对触发器进行大量调整后,我仍然收到“缺少关键字”错误。 –

+0

对不起,我有'On mytable',和'Update,Insert'部件的顺序错误。 –