簡體   English   中英

與主鍵沖突合並

[英]Merge with primary key violation

我有一個基於文件的導入內容,用戶可以在其中發布要導入數據庫中的文件。 將插入新記錄,並更新具有現有ID的記錄。

發布ID為NAME 5 Silly的文件后

他們可以通過發布ID為NAME 5 Sally的新文件來更正此問題

我將文件的批量插入(C#Windows服務)插入了批量表(Sql Server Azure v12)。 這些文件可以包含數百萬行,因此我想避免遍歷行。 批量插入后,我有一個SP進行合並更新/插入並更新已經存在的行並插入新行。

我遇到的問題是,當用戶發布新記錄並更正同一文件中的同一記錄時。 我在目標表上收到主鍵沖突。

有解決這個問題的好方法嗎?

這是一個例子:

--drop table #bulk --drop table #target create table #bulk( id int, name varchar(10) )

insert into #bulk values (1,'John') insert into #bulk values (2,'Sally') insert into #bulk values (3,'Paul') insert into #bulk values (4,'Gretchen') insert into #bulk values (5,'Penny') insert into #bulk values (5,'Peggy') create table #target( id int not null, name varchar(10), primary key (id))

insert into #bulk values (1,'John') insert into #bulk values (2,'Sally') insert into #bulk values (3,'Paul') insert into #bulk values (4,'Gretchen') insert into #bulk values (5,'Penny') insert into #bulk values (5,'Peggy') create table #target( id int not null, name varchar(10), primary key (id))

merge #target as target using(select id, name from #bulk) as bulktable on target.id = bulktable.id when matched then update set target.name = bulktable.name when not matched then insert(id, name) values (bulktable.id, bulktable.name);

這將處理名稱的最新值。

您需要一個用於#bulk的新創建腳本

CREATE TABLE #bulk
(
  row_id int identity(1,1),
  id int,
  name varchar(10)
)

這是可以與新批量表一起使用的腳本:

;WITH CTE as
(
  SELECT
    id, name, 
    row_number() over (partition by id order by row_id desc) rn
    FROM #bulk
), CTE2 as
(
  SELECT id, name
  FROM CTE
  WHERE rn = 1
)
MERGE #target as target
USING CTE2 as bulktable
on target.id = bulktable.id
WHEN matched and 
 not exists(SELECT target.name except SELECT bulktable.name)
 -- this will handle null values. Otherwise it could simply have been: 
 -- matched and target.name <> bulktable.name
THEN update
SET target.name = bulktable.name
WHEN not matched THEN
INSERT(id, name) VALUES (bulktable.id, bulktable.name);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM