2017-09-01 35 views
0

我正在使用SQL Server並想要更新具有特定條件的表。這裏的前提是:更新SQL表而不創建重複項

 
Feature: 
ID FeatureName ApplicationId 
1 Car   5 
2 Car   6 
3 Ship   5 
 
Application: 
ID ApplicationName 
5 Mobile 
6 Server 

現在我想達到兩個目的:

  1. 如果將在Feature表中的重複條目後更新然後刪除舊的條目。
  2. 在表Feature集合ApplicationId6(= Server)其中當前ApplicationId是5(= Mobile)。

因此,最終Feature表應該是這樣的:

 
Feature: 
ID FeatureName ApplicationId 
2 Car   6 
3 Ship   6 

我怎樣才能做到這一點?

+2

你說要6其中值是5,而你的結果是5,而不是6 – jarlh

+0

@jarlh當然,我已經改正了錯誤。 –

回答

1

試試這個:只有

UPDATE Feature SET ApplicationId = 6 WHERE ApplicationId = 5 

DELETE FROM Feature 
LEFT OUTER JOIN (
    SELECT MIN(ID) as RowId, FeatureName, ApplicationId 
    FROM Feature 
    GROUP BY FeatureName, ApplicationId 
)as KeepRows ON 
    Feature.ID = KeepRows.RowId 
WHERE 
    KeepRows.RowId IS NULL 
1

更新有許可證修改exsiting記錄,並且不能刪除或常添加任何東西。我建議只做一次更新以及刪除查詢:

UPDATE Feature 
SET ApplicationId = 6 
WHERE ApplicationId = 5 

WITH cte AS (
    SELECT ID, FeatureName, ApplicationId, 
     ROW_NUMBER() OVER (PARTITION BY FeatureName, ApplicationId ORDER BY ID) rn 
    FROM Feature 
) 

DELETE FROM cte WHERE rn > 1; 
0

希望這會有所幫助。

update feature set applicationid = 6 where applicationid = 5; 


delete from feature where id in (
    select min(id) 
    from feature 
    where featurename in 
      (select featurename 
      from feature f2 
      group by featurename 
      having count(featurename) > 1) 
    and applicationId in 
      (select applicationid 
      from feature f3 
      group by applicationid 
      having count(applicationId) > 1) 
    group by featurename, applicationid; 
) 
; 
0
UPDATE F 
SET F.ApplicationId=(
case when F.ApplicationId=6 then (SELECT ID FROM #Application S WHERE ID=5) 
ELSE ApplicationId 
END) 
FROM #Feature F 

WITH CTE AS 
(
SELECT ID, FeatureName, ApplicationId , ROW_NUMBER() OVER(PARTITION BY FeatureName ORDER BY ApplicationId) rn 
FROM #Feature 
) 

DELETE FROM CTE 
WHERE rn>1 

SELECT * FROM #Feature