最好的方法是使用触发器
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