最好的办法是用一个触发
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
即使尝试对触发器进行大量调整后,我仍然收到“缺少关键字”错误。 –
对不起,我有'On mytable',和'Update,Insert'部件的顺序错误。 –