当几乎同时调用以下代码时,我遇到了麻烦。
DECLARE @membershipIdReturn as uniqueidentifier=null
SELECT @membershipIdReturn = MembershipId
FROM [Loyalty].[Membership]
WITH (NOLOCK)
WHERE ContactId = @customerIdFront
AND
IsDeleted = 0
IF (@membershipIdReturn IS NULL)
//InsertStatementHere
调用非常接近(约为千分之三秒),第二个调用也进入if语句。然后一个单一的失败就是解除,因为这不应该发生。
该错误是因为(NOLOCK)
吗?我需要它来解决交易问题。
是否有任何解决方法可以纠正此行为?
谢谢Al
答案 0 :(得分:1)
两个选项
1.使用唯一约束,然后将insert语句放入Try Catch块
ALTER TABLE [Loyalty].[Membership]
ADD CONSTRAINT uc_ContactId_IsDeleted UNIQUE(ContactId, IsDeleted)
2.使用可序列化提示进行合并。因此,select和insert之间不会有间隙。
MERGE [Loyalty].[Membership] WITH (SERIALIZABLE) as T
USING [Loyalty].[Membership] as S
ON ContactId = @customerIdFront
AND IsDeleted = 0
WHEN NOT MATCHED THEN
INSERT (MemberName, MemberTel) values ('','');