即使我使用正确的索引和查询方案,违反PRIMARY KEY约束

时间:2017-05-09 11:15:54

标签: sql sql-server sql-server-2016 unique-constraint

我有几个独特的索引。例如

SET ansi_nulls ON 

go 

SET quoted_identifier ON 

go 

CREATE TABLE [dbo].[tblrelatedwords] 
  ( 
     [cl_orgwordid]           [BIGINT] NOT NULL, 
     [cl_relatedwordid]       [BIGINT] NOT NULL, 
     [cl_relatedwordtypecode] [SMALLINT] NOT NULL, 
     [cl_relation_sourceid]   [TINYINT] NOT NULL, 
     CONSTRAINT [PK_tblSeeAlso] PRIMARY KEY CLUSTERED ( [cl_orgwordid] ASC, 
     [cl_relatedwordid] ASC, [cl_relatedwordtypecode] ASC )WITH (pad_index = OFF 
     , statistics_norecompute = OFF, ignore_dup_key = OFF, allow_row_locks = on, 
     allow_page_locks = on, FILLFACTOR = 90) ON [PRIMARY] 
  ) 
ON [PRIMARY] 

go 

ALTER TABLE [dbo].[tblrelatedwords] 
  ADD CONSTRAINT [DF_tblSeeAlso_cl_RelatedWordTypeCode] DEFAULT ((255)) FOR 
  [cl_RelatedWordTypeCode] 

go 

当我使用下面的查询系统即使我检查如果不存在,我仍然得到以下错误

IF NOT EXISTS
  ( SELECT 1
   FROM tblRelatedWords
   WHERE (cl_OrgWordId=@cl_OrgWordId
          AND cl_RelatedWordId=@cl_RelatedWordId
          AND cl_RelatedWordTypeCode=@cl_RelatedWordTypeCode)
     OR (cl_OrgWordId=@cl_RelatedWordId
         AND cl_RelatedWordId=@cl_OrgWordId
         AND cl_RelatedWordTypeCode=@cl_RelatedWordTypeCode) ) BEGIN
INSERT INTO tblRelatedWords
VALUES (@cl_OrgWordId,
        @cl_RelatedWordId,
        @cl_RelatedWordTypeCode,
        @cl_Relation_SourceId) END

错误

Violation of PRIMARY KEY constraint 'PK_tblSeeAlso'. Cannot insert duplicate key in object 'dbo.tblRelatedWords'. The duplicate key value is (11439364, 2495501, 243).  The statement has been terminated.

是的,多个线程正在添加到同一个表中但是不是IF NOT EXISTS应该阻止这种情况吗?

Microsoft SQL Server 2016(SP1-CU2)(KB4013106) - 13.0.4422.0(X64)

0 个答案:

没有答案