为什么我得到sql错误“违反PRIMARY KEY约束”

时间:2015-06-05 18:10:34

标签: sql tsql transactions sql-update sql-insert

我有一张桌子

CREATE TABLE [dbo].[DocGenVariable](
[userkey_sessionid] [varchar](38) NOT NULL,
[is_session] [bit] NULL,
[var_name] [nvarchar](255) NOT NULL,
[var_value] [nvarchar](1000) NOT NULL,
[topic_id] [varchar](38) NOT NULL,
[resource_id] [int] NULL,
[added] [datetime] NOT NULL,

CONSTRAINT [PK_DocGenVariable] PRIMARY KEY CLUSTERED 
(
    [userkey_sessionid] ASC,
    [var_name] ASC,
    [topic_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

有时(注意>有时)我收到错误

"Violation of PRIMARY KEY constraint 'PK_DocGenVariable'. 
Cannot insert duplicate key in object 'dbo.DocGenVariable'.

当我尝试在此表中添加条目时

delete from DocGenVariable where userkey_sessionid = @key_session and var_name = @var_name and topic_id = @topic_id 

if (LTRIM(RTRIM(@var_value)) <> '')
    begin
        insert into DocGenVariable(userkey_sessionid, is_session, var_name, var_value, topic_id, resource_id, added)
        values (@key_session, @is_session, @var_name, @var_value, @topic_id, @resource_id, GetDate())
    end

我首先要做的是删除必须更新的条目,然后添加一个新条目。

为什么我会遇到此约束错误?

2 个答案:

答案 0 :(得分:1)

为什么删除然后插入?只需更新它。

IF EXISTS(select 1 from DocGenVariable where userkey_sessionid = @key_session 

var_name = @var_name and topic_id = @topic_id) 
BEGIN
    UPDATE ....
    END ELSE BEGIN
    INSERT ... 
END

答案 1 :(得分:1)

尝试upsert

 using DocGenVariable target 
 using DocGenVariable source  
    on source.userkey_sessionid = @key_session     
   and source.var_name = @var_name     
   and source.topic_id = @topic_id   
   and target.userkey_sessionid = @key_session     
   and target.var_name = @var_name     
   and target.topic_id = @topic_id  
  when match 
       set target.resource_id = @resource_id 
         , target .added = GetDate()   
  when not matched then
       insert into DocGenVariable(userkey_sessionid, is_session, var_name, var_value, topic_id, resource_id, added)
       values (@key_session, @is_session, @var_name, @var_value, @topic_id, @resource_id, GetDate())