更新表中的重复字段

时间:2013-03-28 13:16:20

标签: sql sql-server tsql sql-server-2008-r2 sql-update

我有大约100000条记录的表。我需要像这样更新相同的字段。 例如,这是我的表

id     name
 1     sss
 2     bbb
 3     ccc
 4     avg
 5     bbb
 6     bbb
 7     sss
 8     mmm
 9     avg

执行脚本后我需要

id     name
 1     sss
 2     bbb
 3     ccc
 4     avg
 5     bbb-5
 6     bbb-6
 7     sss-7
 8     mmm
 9     avg-9

我该怎么做?

2 个答案:

答案 0 :(得分:3)

使用CTE

WITH greaterRecord 
AS 
(
    SELECT  id, 
            name, 
            ROW_NUMBER() OVER(PARTITION BY name ORDER BY id) RN
    FROM    TableName
)
UPDATE greaterRecord
SET    name = name + '-' + CAST(id AS VARCHAR(10))
WHERE  RN > 1

这是适用于大多数RDBMS的常见查询

UPDATE  a
SET     a.Name = a.Name + '-' + CAST(ID AS VARCHAR(10))
FROM    tableName a
        LEFT JOIN
        (
            SELECT  MIN(ID) min_ID, name
            FROM    tableName
            GROUP   BY name
        ) b ON  a.name = b.name AND
                a.ID = b.Min_ID
WHERE   b.Name IS NULL

执行update语句后的OUTPUT

╔════╦═══════╗
║ ID ║ NAME  ║
╠════╬═══════╣
║  1 ║ sss   ║
║  2 ║ bbb   ║
║  3 ║ ccc   ║
║  4 ║ avg   ║
║  5 ║ bbb-5 ║
║  6 ║ bbb-6 ║
║  7 ║ sss-7 ║
║  8 ║ mmm   ║
║  9 ║ avg-9 ║
╚════╩═══════╝

答案 1 :(得分:3)

这应该做:

;WITH CTE AS 
(
    SELECT  id, 
            name, 
            RN = ROW_NUMBER() OVER(PARTITION BY name ORDER BY id)
    FROM YourTable
)
UPDATE CTE
SET name = name + '-' + CAST(id AS VARCHAR(8))
WHERE RN > 1