Sql 违反主键约束,即使我使用了正确的索引和查询方案
我有几个唯一的索引。比如说Sql 违反主键约束,即使我使用了正确的索引和查询方案,sql,sql-server,sql-server-2016,unique-constraint,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] [SMALL
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
错误
是的,多个线程正在添加到同一个表中,但是如果不存在线程,则不应该防止这种情况发生
Microsoft SQL Server 2016(SP1-CU2)(KB4013106)-13.0.4422.0(X64)您在查询时使用的事务隔离级别是什么?数据库的默认设置是什么?您可以使用
merge
语句。或者,您可以将批包含到事务中,并在中使用和(updlock)
提示(如果存在)(选择…
查询的一部分。不存在
和插入
是两个独立的操作,因此它们之间有一个间隙,可以插入相同的记录。有关SQL Server中竞争条件的详细信息,据我所知,最好的线程安全解决方案是使用合并(HOLDLOCK)
如前所述。@alroc无论默认值是什么is@Arvo你能把你的答案贴出来吗
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.