如何更新SQL Server中重复行的列

时间:2016-02-08 10:48:44

标签: sql-server-2012

我的表格tUser包含usernamepasswordemailActive列。

我需要将重复行的Active列设置为0.我怎样才能实现此目的?

例如:表值为

UserName    Password   Email             Active
-----------------------------------------------
Demo        demo       abc@gmail.com       1
Demo        demo       abc@gmail.com       1
Demo        demo       abc@gmail.com       1

我需要将此值更改为

Demo demo abc@gmail.com 1

,其他2行应为

Demo demo abc@gmail.com 0
Demo demo abc@gmail.com 0

1 个答案:

答案 0 :(得分:1)

如果您的表格中有主键唯一标识每一行,那么您可以使用CTE和此方法清除任何重复项:

;WITH Duplicates AS
(
    SELECT
        UserID, Username, Password, Email, Active,
        RowNum = ROW_NUMBER() OVER (PARTITION BY Username, Email ORDER BY UserID)
    FROM
        tUser
)
UPDATE tUser
SET Active = 0
FROM Duplicates d
WHERE d.UserID = tUser.UserID
  AND d.RowNum > 1