2012-11-03 92 views
1

如何避免表中的重複插入?我使用下面的查詢中插入到表:SQL如何避免表中的重複插入

insert into RefundDetails(ID,StatusModified,RefundAmount,OrderNumber) 
    select 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') 
+1

使用** ** UNIQUE .. –

回答

0

取決於您使用DB但不是你尋找類似的rownum < 2返回頂端行?

1

使用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/

1

您可以創建將值插入表中的過程。

create procedure p_insert_tablename 
columname datatype, 
coluname datatype 
begin 
if exists(select 1 from tblname where [give the condition on which you cols value you dont want the duplicate value]) 
/*if true then update the value by update query using the condition */ 
/*dont forget to give condition in update query*/ 

else 

/*insert the value*/ 
exit 

要調用程序

exec p_insert_tablename col1, col2,... 
0
To ignore (with a warning) attempts to insert duplicate keys rather than raising an error and having the whole statement fail you can use the IGNORE_DUP_KEY option. 

    CREATE TABLE RefundDetails 
    (
    ID INT NOT NULL PRIMARY KEY NONCLUSTERED WITH (IGNORE_DUP_KEY = ON), 
    ... 
    --your columns 
    )