在插入sql之前删除重复项

时间:2014-11-12 17:25:56

标签: sql sql-server

我有临时表#tempRD,我试图将结果集插入表中,如下所示:

insert into Routing (RoutingKeyID, LocationID, Data, ServiceID, CountryID)
   select 
       rk.ID, rd.LocationID, rd.Data, rd.service, rd.CountryID
   from 
       #tempRD rd
   inner join 
       RoutingKey rk on rk.serviceID = @ID and rk.Name=rd.[Key]

现在,当发生这种情况时,我会收到重复的密钥错误

  

无法在对象中插入重复的关键字' dbo.Routing'具有唯一索引' UIX_Routing_RoutingKeyID_CountryID'。重复键值为(51,433)

如何在插入之前检查routingkeyidcountryid之前的行是否已存在?

我用光标做了这个,但需要很长时间。

4 个答案:

答案 0 :(得分:0)

insert into Routing (RoutingKeyID, LocationID, Data, ServiceID, CountryID)

select *
from (
select rk.ID, rd.LocationID, rd.Data, rd.service, rd.CountryID, rank() over(partition by rk.ID, rd.CountryID order by rd.LocationID, rd.Data, rd.Service) as rnk
from #tempRD rd
inner join RoutingKey rk on rk.serviceID = @ID and rk.Name=rd.[Key]
) a
where rnk = 1

使用rank() over(partition by ... order by ....),您可以创建具有rk.ID, rd.CountryID重复组合的记录的排名。最后,您应用WHERE子句仅使用第一次出现的组合。

如果其他字段也是重复的,您也可以使用select distinct。我没有尝试过代码,可能会有拼写错误; - )

答案 1 :(得分:0)

试试这个?

INSERT INTO 
    Routing (
        RoutingKeyID, 
        LocationID, 
        Data, 
        ServiceID, 
        CountryID)
SELECT 
    rk.ID, 
    rd.LocationID, 
    rd.Data, 
    rd.[service], 
    rd.CountryID
FROM 
    #tempRD rd
    INNER JOIN RoutingKey rk ON rk.serviceID = @ID AND rk.Name = rd.[Key]
    LEFT JOIN Routing r ON r.RoutingKeyID = rk.ID AND r.CountryID = rd.CountryID
WHERE
    r.RoutingKeyID IS NULL;

答案 2 :(得分:0)

使用Row_number窗口功能,您可以找到重复项。注意我已经通过id desc命令获得最新的重复记录。

;WITH cte
     AS (SELECT Row_number() OVER(partition BY RoutingKeyID, CountryID ORDER BY id DESC) rn,
                rk.ID,
                rd.LocationID,
                rd.Data,
                rd.service,
                rd.CountryID
         FROM   #tempRD rd)
INSERT INTO Routing
            (RoutingKeyID,LocationID,Data,ServiceID,CountryID)
SELECT rk.ID,
       rd.LocationID,
       rd.Data,
       rd.service,
       rd.CountryID
FROM   cte
WHERE  rn = 1 

答案 3 :(得分:0)

可以使用类似

的内容
MERGE INTO Routing 
USING (SELECT @RoutingKeyID, @LocationID, @Data, @ServiceID, @CountryID) AS source (RoutingKeyID, LocationID, Data, ServiceID, CountryID)
ON (Routing.RoutingKeyID= source.RoutingKeyID)
WHEN NOT MATCHED THEN 
INSERT (RoutingKeyID, LocationID, Data, ServiceID, CountryID)
VALUES (source.RoutingKeyID, source.LocationID, source.Data, source.ServiceID, source.CountryID)