使用 DISTINCT 关键字从您的选择语句中删除重复项
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/