SQL如何避免在表中重复插入

时间:2012-11-03 10:46:54

标签: 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') 

4 个答案:

答案 0 :(得分: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 :(得分: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,...

答案 2 :(得分:0)

取决于你使用的数据库,但你不是在寻找像rownum&lt; 2返回最上面的行?

答案 3 :(得分: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  
   )