如果其中一个字段在SQL中具有多个相同的值,则如何更新值

时间:2016-07-25 07:24:06

标签: sql sql-server

在我的数据库表中,其中一个字段具有相同的值。我想用随机数或字符串更改此值,该字符串附加到此字段值以获得唯一性。

示例数据 这里'Ma' has 5 records等等。我想更改名称Ma01, Ma02等。

Id  Name  Count
1   Ma   5
2   Ga   6
3   Gu   5

如何使用SQL查询

4 个答案:

答案 0 :(得分:2)

试试这个

UPDATE TBL
SET Name = A.Name
FROM
(
    SELECT
        Id,
        Name + CAST(ROW_NUMBER() OVER (PARTITION BY Name ORDER BY (SELECT NULL)) AS NVARCHAR(500)) AS NAME,
        Count
    FROM
        TBL
    WHERE
        NAME IN 
        (
            SELECT T.NAME FROM TBL T
            GROUP BY T.NAME
            HAVING COUNT(1) > 1
        )

) A
WHERE
    TBL.Id = A.ID

答案 1 :(得分:0)

试试这个:

Select Name + convert(varchar(2), row_number()over(partition by Name order by Name))
From tablename

答案 2 :(得分:0)

你试试这个。

Declare @i int  = 1

update yourtable
set ID  = @i , @i = @i + 1

答案 3 :(得分:0)

根据NEER的代码选择代码,添加前导零,在MSSQL数据库上测试。

SELECT
    Id,
    Name,
    Name + RIGHT('00'+CAST(ROW_NUMBER() OVER (PARTITION BY Name ORDER BY (SELECT Name)) AS NVARCHAR(MAX)),2) AS Updatedname

FROM
    tablename
WHERE
    Name IN 
    (
        SELECT T.NameFROM tablename T
        GROUP BY T.Name
        HAVING COUNT(Name) > 1
    )
GROUP BY Name,Id
ORDER BY Name