更新SQL表而不创建重复项

时间:2017-09-01 09:18:40

标签: sql sql-server sql-update

我正在使用SQL Server并希望更新具有特定条件的表。这是前提:

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)。
  3. 所以最终的Feature表应如下所示:

    Feature:
    ID  FeatureName  ApplicationId
    2   Car          6
    3   Ship         6
    

    我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:1)

试试这个:

UIApplication.shared.statusBarStyle = .default // Dark content, for use on light backgrounds

答案 1 :(得分:1)

更新仅具有修改现有记录的许可,并且无法正常删除或添加任何内容。我建议您在单个事务中执行更新以及删除查询:

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;

答案 2 :(得分: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;
)
;

答案 3 :(得分: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