Merge Statement SSIS

耗尽温柔 提交于 2019-12-11 14:51:58

问题


I tested this code on SSMS

Merge dim_BTS AS Target using  
(
    SELECT  A.BTS, D.idVille  
    FROM onAir A  
    INNER JOIN dbo.DIM_AXE_GEO D   
        ON A.Ville = D.Villle   

) AS Source ON Source.BTS = Target.BTS  


WHEN MATCHED THEN  
UPDATE  
SET Target.idVille = Source.idVille;  

show me this error

The MERGE statement attempted to UPDATE or DELETE the same row more
than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.

Can you please help me what can I do ?


回答1:


Your Source sub-query is returning duplicate rows with same BTS (column You use to join on target) which is not allowed for MERGE statement.

You can refine your query to filter only the latest row for each BTS using ROW_NUMBER() function in CTE

WITH CTE_Source AS 
(
    SELECT  A.BTS, D.idVille, ROW_NUMBER() OVER (PARTITION BY A.BTS ORDER BY d.idVille DESC)  RN -- choose order of your preference
    FROM onAir A  
    INNER JOIN dbo.DIM_AXE_GEO D   
        ON A.Ville = D.Villle   
)
Merge dim_BTS AS Target using  
(
    SELECT  * FROM CTE_Source WHERE RN=1
) AS Source ON Source.BTS = Target.BTS  
WHEN MATCHED THEN  
UPDATE  
SET Target.idVille = Source.idVille; 

Or if multiple row BTS needs to be inserted, you need to add more columns on ON clause when joining on target.




回答2:


Have a look at your SELECT statement. You may have to add DISTINCT, or another JOIN condition, or a WHERE clause to make sure rows are not duplicated.



来源:https://stackoverflow.com/questions/17720727/merge-statement-ssis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!