删除脚本的SQL Server 2008(Delete script SQL Server 2008

2019-08-01 12:37发布

下面是我试图解决的情况。 我有一个装载有重复的表。 它的发生是因为类似的行是从两个不同的来源加载。 在包被照顾。

但是,我想删除那些重复的行。 这里没有关键属性(我不能使用没有PK)。 两个来源是克利夫兰市和俄亥俄州。 和我有一列,从该源的行,由(加载示出DataSource列)。

因此,该行中它显示为DataSource = 'Cleveland'DataSource = 'OhioState'

下面是我坚持的样本。 你们可以有不同的方法来删除这些行雷似乎并不很好地工作? 再次感谢你们。我不认为我试图接近的方式是正确的,甚至...

    IF OBJECT_ID('tempdb..#Ohio') IS NOT NULL 
     BEGIN 
     DROP TABLE #Ohio
     END 

  ;WITH Oh AS 
    ( SELECT ROW_NUMBER()OVER
      (
        PARTITION by UID,ADDRESS,CITY,STATE,Zip
          ORDER BY 
            UID
       ) AS IA,UID,ADDRESS,City,State,Zip FROM F_staRes
     ) 
    SELECT * INTO #Ohio   FROM Oh WHERE IA> 1   AND  DataSource='Ohio'  

    IF OBJECT_ID('tempdb..#Clevland') IS NOT NULL 
    BEGIN 
   DROP TABLE #Clevland
   END 

    ;WITH Cle AS 
     ( SELECT ROW_NUMBER()OVER
      (
           PARTITION by UID,ADDRESS,CITY,STATE,Zip
       ORDER BY 
        UID
         ) AS CE,UID,ADDRESS,City,State,Zip FROM F_staRes
         ) 
   SELECT * INTO #Clevland   FROM Cle WHERE CE> 1  AND  DataSource!='Ohio' 

    select * from #Clevland--I want to delete this records
     Intersect 
     select * from #Ohio

Answer 1:

  1. 我认为最关键的词INTERSECT不能正常使用。 解释如下。 你可以按照链接以获取详细信息。

EXCEPT返回从左侧查询是不是也右边查询发现任何不同的值。 INTERSECT返回由双方在INTERSECT操作数的左,右两侧的查询返回任何不同的值

http://msdn.microsoft.com/zh-cn/library/ms188055.aspx

  1. 为了实现自己的perpose,你可以尝试的命令合并。

     ; merge into #Clevland as target using #Ohio as source on (target.UID = source.UID) -- you could add ADDRESS,City,State,Zip when not matched insert into target (UID) values (source.UID) ; 

希望这会有所帮助。



Answer 2:

也许这会帮助你

;WITH cte AS
 (
  SELECT ROW_NUMBER() OVER (PARTITION BY UID, ADDRESS, City, State, Zip, DataSource ORDER BY UID) AS Dup
  FROM dbo.F_staRes
  )
DELETE cte
WHERE Dup > 1


文章来源: Delete script SQL Server 2008