1

如何避免在表中重复插入?我使用下面的查询插入到表中:

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

4 回答 4

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,...
于 2012-11-03T10:56:59.957 回答
1

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

于 2012-11-03T10:53:18.440 回答
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  
   ) 
于 2012-11-03T14:52:42.610 回答
0

取决于您使用的数据库,但您不是在寻找类似 rownum < 2 的东西,它返回最上面的行吗?

于 2012-11-03T10:52:56.100 回答