SQL服务器,同时双插入,unicity Bug

SQL Server, double insert at the exact same time, unicity Bug

当下面的代码几乎同时被调用两次时,我遇到了麻烦。

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)的bug吗?我需要它来解决交易问题。

是否有解决此问题的解决方法?

谢谢艾尔

两个选项

1.Use 唯一约束然后将您的插入语句放入 Try Catch 块

ALTER TABLE [Loyalty].[Membership] 
ADD CONSTRAINT uc_ContactId_IsDeleted UNIQUE(ContactId, IsDeleted)

2.Use 与可序列化提示合并。因此,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 ('','');