1

我遇到了主键违规,我不知道如何解决它。实际的错误信息是;

消息 2627,级别 14,状态 1,第 1 行违反主键约束“PK_infmtx_dat_Transactions”。无法在对象“dbo.infmtx_dat_Transactions”中插入重复键。

我的代码如下:

INSERT INTO infmtx_dat_Transactions (tranid,chgid,chgidagnst,incnumagnst,rptpd,aid,claimid
,chgsvcpd,trantype,doschg,doscalpd,postdtchg,postdtchgcalpd,postdttran
,postdttrancalpd,depositdt,depositcalpd,cptid,cptcode,cptcomp,billprov
,rendprov,facid,posid,dptid,priminsmne,priminscatid,transcode,crcat
,refprovid,modalid,units,adjunits,patcnt,enccnt,cptcnt,amt,chgallow
,totworkrvu,totfacrvu,denial,curresponsible,curbal,curinsmne
,curopenbalflag,curcreditbalflag,denyflag,denycode,denydate,feetypeid )
SELECT
trn.tran_id
,trn.chg_id
,chg.chgidagnst
,chg.incnumagnst
,trn.rptpd
,trn.acctid
,chg.claimid
,chg.rptpd
,tcd.trantype
,chg.doschg
,chg.doscalpd
,chg.postdtchg
,chg.postdtchgcalpd
,trn.tranpostdt
,trn.tranpostpd
,trn.pmtdate
,trn.pmtpd
,chg.cptid
,chg.cptcode
,chg.cptcomp
,chg.billprov
,chg.rendprov
,chg.facid
,chg.posid
,chg.dptid
,chg.priminsmne
,chg.priminscatid
,trn.payermne
,tcd.crcat
,chg.refprovid
,chg.modalid
,0
,0
,0
,0
,0
,trn.trnamt
,chg.chgallow
,0
,0
,0
,''
,0
,''
,'N'
,'N'
,'N'
,''
,Null
,chg.feetypeid
FROM tmp_dat_OtherTrans trn
LEFT JOIN infmtx_dat_Transactions chg on trn.chg_id = chg.tranid AND trn.chg_id = chg.chgid
AND trn.chg_id = chg.chgidagnst 
LEFT JOIN infmtx_dic_TransCode tcd on trn.payermne = tcd.trancodemne
ORDER BY trn.tran_id;

我将如何设置查询以查找重复记录。
表上的主键infmtx_dat_Transactions有:tranid、chgid、chgidagnst、rptpd和trantype

4

2 回答 2

1

主键(和其他候选键)防止插入重复值,因此您无法搜索它们。不存在重复项。

相反,在您尝试插入的新数据中找到主键(和其他候选键)值,然后搜索它们。其中一个肯定在您的新数据中重复,或者已经在您的表中。

看起来您可以通过在源表“tmp_dat_OtherTrans”(包括其连接)和“infmtx_dat_Transactions”之间执行内部连接来识别现有表中的冲突键。

于 2013-07-12T16:35:12.557 回答
0
WITH duplicate_check AS (
  SELECT 
    *,ROW_NUMBER() OVER(PARTITION BY key_column1,key_column2,key_column3 ORDER BY (SELECT NULL))) AS n
  FROM table_with_suspect_data
SELECT
  *
FROM duplicate_check
WHERE n > 1

For deleting all rows except one for each duplicate:

 WITH duplicate_check AS (
  SELECT 
    *,ROW_NUMBER() OVER(PARTITION BY key_column1,key_column2,key_column3 ORDER BY (SELECT NULL))) AS n
  FROM table_with_suspect_data
DELETE
FROM duplicate_check
WHERE n > 1
于 2013-07-12T16:40:34.407 回答