如果数据当前不存在,我正尝试将表A中的数据添加到表B.当我将它作为一个select语句运行时,一切看起来都是正确的。当我添加insert语句时,我收到错误“无法在对象'dbo.inonhd'中插入具有唯一索引'PARTLOCA'的重复键行。”。我写的代码应该防止重复。有人可以指出我做错了什么吗?
insert into inonhd
(fpartno
,fpartrev
,fbinno
,flocation
,fonhand
,fac
,fcudrev)
SELECT INMAST.fpartno
,INMAST.frev
,inmast.fbin1
,inmast.flocate1
,inmast.fonhand
,inmast.fac
,inmast.frev
FROM INMAST
LEFT JOIN INONHD
ON INMAST.FPARTNO + INMAST.FREV = INONHD.FPARTNO + INONHD.FPARTREV
where INMAST.fpartno like 'gs-%'
and inmast.fonhand = '0'
and inonhd.fpartno is null
答案 0 :(得分:1)
假设PartNo和Location是唯一索引的一部分,请使用以下sql查找导致错误的行:
select fpartno,flocation, ct
from
(SELECT INMAST.fpartno as fpartno , inmast.flocate1 as flocation
, count(0) ct
FROM INMAST
LEFT JOIN INONHD
ON INMAST.FPARTNO + INMAST.FREV = INONHD.FPARTNO + INONHD.FPARTREV
where INMAST.fpartno like 'gs-%'
and inmast.fonhand = '0'
and inonhd.fpartno is null
group by INMAST.fpartno, inmast.flocate1 ) t
where t.ct > 1
答案 1 :(得分:0)
您正在对两列进行连接并进行匹配,因此您可能需要在这两列上检查NULL条件 唯一索引是复合键 - FPARTNO和FREV?
and inonhd.fpartno is null and inonhd.FREV is null
最好还是使用MERGE
MERGE INONHD as target
USING ( SELECT INMAST.fpartno
,INMAST.frev
,inmast.fbin1
,inmast.flocate1
,inmast.fonhand
,inmast.fac
,inmast.frev
FROM INMAST ) as source ( frev, fbin1, flocate1, fonhand, fac, frev)
ON fonhand = '0'
and fpartno is null
and INMAST.FPARTNO + INMAST.FREV = INONHD.FPARTNO + INONHD.FPARTREV
WHEN NOT MATCHED THEN
INSERT (fpartno
,fpartrev
,fbinno
,flocation
,fonhand
,fac
,fcudrev)
VALUES (source.fpartno
,source.fpartrev
,source.fbinno
,source.flocation
,source.fonhand
,source.fac
,source.fcudrev)
答案 2 :(得分:0)
同意Rajesh, 如果您使用的是Merge,则不需要" 并且fpartno为null "过滤 我们可以在源代码sql中应用其他过滤器
MERGE INONHD as target
USING ( SELECT INMAST.fpartno
,INMAST.frev
,inmast.fbin1
,inmast.flocate1
,inmast.fonhand
,inmast.fac
,inmast.frev
FROM INMAST
WHERE INMAST.fpartno like 'gs-%'
and inmast.fonhand = '0') as source ( frev, fbin1, flocate1, fonhand, fac, frev)
ON INMAST.FPARTNO + INMAST.FREV = INONHD.FPARTNO + INONHD.FPARTREV
WHEN NOT MATCHED AND THEN
INSERT (fpartno
,fpartrev
,fbinno
,flocation
,fonhand
,fac
,fcudrev)
VALUES (source.fpartno
,source.fpartrev
,source.fbinno
,source.flocation
,source.fonhand
,source.fac
,source.fcudrev)