在SQL Server中,如何防止INSERT INTO SELECT查询中出现重复

在SQL Server中,如何防止INSERT INTO SELECT查询中出现重复,sql,sql-server,Sql,Sql Server,我想防止在表中插入重复的值来解决这个问题,我使用的语法是“WHERE NOT EXISTS”,但不起作用,所以请选择正确的语法来解决这个问题 INSERT INTO [JPCustomer] ([CustomerID ], [JPID], [Frequency], [StartWeek],

我想防止在表中插入重复的值来解决这个问题,我使用的语法是“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)

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

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
)

您的select语句中是否已存在重复项?您可以通过触发器进行检查。。。