在SQL Server中如何防止INSERT INTO SELECT查询中的重复

时间:2017-09-04 14:42:47

标签: sql sql-server

我想阻止表中的插入重复值来解决这个问题我使用语法" WHERE NOT EXISTS"但是没有工作,请问解决这个问题的正确语法是什么。

INSERT INTO [JPCustomer] ([CustomerID ],
                           [JPID],
                           [Frequency],
                           [StartWeek],
                           [sat],
                           [sun],
                           [mon],
                           [tue],
                           [wed],
                           [thu],
                           [fri],
                           [VisitOrder],
                           [ModifiedOn],
                           [ModifiedBy],
                           [CreatedOn],
                           [Createdby],
                           [RecordSource],
                           [IsPotential])
select cu.CustomerNo,
       jp.ID,
        4,
       1,
        1,
        1,
        1,
        1,
        1,
        1,
        1,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        0,
        0 
from CUSTOMERNO# cu
join SalesmanNo# sa on cu.OCCURRENCE = sa.OCCURRENCE
join JourneyPlan JP on jp.AssignedTO = sa.SalesmanNo
WHERE NOT EXISTS (select j.CustomerID,j.JPID from JPCustomer j)

1 个答案:

答案 0 :(得分:3)

您不存在的位置无法正确比较:

WHERE NOT EXISTS 
(
select 1 -- does not matter what you return, exists will be true if any value comes back
from JPCustomer j 
where j.CustomerID = cu.customerid  -- match on customerid field
and j.JPID = jp.id  -- match on id field
)