2

我有大约 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

我怎样才能做到这一点?

4

2 回答 2

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

更新语句执行后的输出

╔════╦═══════╗
║ ID ║ NAME  ║
╠════╬═══════╣
║  1 ║ sss   ║
║  2 ║ bbb   ║
║  3 ║ ccc   ║
║  4 ║ avg   ║
║  5 ║ bbb-5 ║
║  6 ║ bbb-6 ║
║  7 ║ sss-7 ║
║  8 ║ mmm   ║
║  9 ║ avg-9 ║
╚════╩═══════╝
于 2013-03-28T13:19:09.720 回答
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
于 2013-03-28T13:20:05.740 回答