使用DISTINCT關鍵字來從你的SELECT語句刪除重複
insert into RefundDetails
(ID,StatusModified,RefundAmount,OrderNumber)
select distinct
O.id
,O.StatusModified
,OI.RefundAmount
,O.OrderNumber
from Monsoon.dbo.[Order] as O WITH (NOLOCK)
JOIN Monsoon.dbo.OrderItem as OI WITH (NOLOCK)
on O.Id = OI.OrderId
WHERE o.ID in
(
SELECT OrderID
FROM Mon2QB.dbo.monQB_OrderActivityView
WHERE ACTIVITYTYPE = 4
AND at BETWEEN '10/30/2012' AND '11/3/2012'
)
AND O.StatusModified < '11/3/2012'
,或者如果您擔心的表已經包含了一些值,指定只有地方插入新條目不是已經在那裏:
insert into RefundDetails
(ID,StatusModified,RefundAmount,OrderNumber)
select distinct
O.id
,O.StatusModified
,OI.RefundAmount
,O.OrderNumber
from Monsoon.dbo.[Order] as O WITH (NOLOCK)
JOIN Monsoon.dbo.OrderItem as OI WITH (NOLOCK)
on O.Id = OI.OrderId
WHERE o.ID in
(
SELECT OrderID
FROM Mon2QB.dbo.monQB_OrderActivityView
WHERE ACTIVITYTYPE = 4
AND at BETWEEN '10/30/2012' AND '11/3/2012'
)
AND O.StatusModified < '11/3/2012'
--assuming we just need to check o.id to determine a duplicate:
and O.id not in
(
select o.id
from RefundDetails
)
--alternatively, if the entire record counts as a duplicate
and not exists
(
select top 1 1
from RefundDetails b
where O.id = b.id
and O.StatusModified = b.StatusModified
and OI.RefundAmount = b.RefundAmound
and O.OrderNumber = b.Order Number
最後,如果你想要的東西更先進的(即允許插入新訂單和更新現有的),如果你使用SQL或Oracle,你有MERGE語句:http://blog.sqlauthority.com/2008/08/28/sql-server-2008-introduction-to-merge-statement-one-statement-for-insert-update-delete/
使用** ** UNIQUE .. –