Rename the duplicate entries.

  • I have column named HouseName in a table-discpline , that has got duplicate names i.e.

    Test1

    Test1

    Test2

    Test2

    Test2

    Test3

    Test4

    The expected output is(i.e. replace the names with *_1 ,*_2 and so on when the names are duplicating,Leave the unique names as it is)

    Test1

    Test1_1

    Test2

    Test2_1

    Test2_2

    Test3

    Test4

  • This may help.

    ;WITH mytable AS

    (SELECT * FROM (

    VALUES('Test1'),('Test1'),('Test2'),('Test2'),('Test3'),('Test4')

    )x(y))

    , plusrownum AS

    (SELECT row_number() OVER (PARTITION BY y ORDER BY y) AS rownum,y FROM mytable)

    SELECT y + CASE WHEN plusrownum.rownum<>1 THEN '_' + cast(plusrownum.rownum-1 AS VARCHAR) ELSE '' END FROM plusrownum

  • Thanks. But i need an update script to Update the records directly in DataBase.

  • ...then use the script I provided, and change the last select into an update.

  • Can you please modify the query to Update .Thanks !

  • Changing Select to Update doesn't work.Can you please post the UPDATE Query .Thanks !

  • I took the result set into temp table (that had name ,id) and then looped through its records(using while loop) and updated the original table. Thanks !

  • Try:

    with CTE_RN as

    (

    select

    *,

    ROW_NUMBER() OVER(PARTITION BY HouseName ORDER BY HouseName) as RN

    from discpline

    )

    update CTE_RN

    set HouseName = HouseName + '_' + cast(RN - 1 as varchar)

    where RN > 1

    Hope this helps.

Viewing 8 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic. Login to reply