2017-09-04 59 views
1

我想阻止表中插入重複值來解決此問題我使用語法「WHERE NOT EXISTS」但不工作,所以請解決什麼是正確的語法來解決這個問題。SQL Server中如何防止INSERT INTO SELECT查詢中的重複項

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) 
+0

你已經在你的SELECT語句重複? –

+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 
) 
+0

感謝您的支持,解決了問題 –