如何检测一张表中某字段是否有重名,如果有,则改变一个名字,方法是给名字的后面加一个数字

解决方案 »

  1.   

    大概意思update t set col = case when rn>1 then col+ltrim(rn-1) else col end
    from (select rn=row_number()over(partition by col order by getdate()) from tb) t
      

  2.   


    -- This ???
    declare @tab table (id int identity, c varchar(10));
    insert into @tab (c)
     select 'A' union all select 'B' union all
     select 'A' union all select 'B';
    ;with t as(
    select *, row_number() over (partition by c order by id) rn from @tab
    )
    update t set c=c+ltrim(rn) where rn>1;select * from @tab;
    /*
    1 A
    2 B
    3 A2
    4 B2
    */