最良の方法はトリガーを使用することです
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 句はパフォーマンスのみを目的としており、トリガーをトリガーする update または insert によって挿入または更新された 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