日期:2014-05-17  浏览次数:20515 次

修改重复列
CREATE TABLE [dbo].[testx1]
(
[id] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL
)
insert into testx1 VALUES('A')
insert into testx1 VALUES('A')
insert into testx1 VALUES('B')
insert into testx1 VALUES('C')
insert into testx1 VALUES('C')
insert into testx1 VALUES('C')
insert into testx1 VALUES('D')
insert into testx1 VALUES('A1')
insert into testx1 VALUES('D')
insert into testx1 VALUES('B')

修改后结果为
1 A
2 A2
3 B
4 C
5 C1
6 C2
7 D
8 A1
9 D1
10 B1

即原本表中有A,A,A1,更新后为A,A2,A1

------解决方案--------------------
SELECT id,NAME=LEFT(NAME,1)+ISNULL(NULLIF(RTRIM(ROW_NUMBER() OVER (PARTITION BY LEFT(NAME,1) ORDER BY id)-1),'0'),'')
FROM [testx1]

------解决方案--------------------
你这个貌似只能用循环了,有个id再,顺序不好改变。
------解决方案--------------------
select id ,name+case when c=0 then '' else cast(c as varchar(4)) end   from 
( select id,  name, (select count(*) from testx1 as b  where a.name=b.name and a.id>b.id  ) as c
 from testx1 as a ) as a
------解决方案--------------------

create function fn_split(@name varchar(200))
returns varchar(200)
as
begin
declare @sub varchar(200)
declare @index int
set @index=1
set @sub=substring(@name,@index,1)
while 1=1
begin
if(@sub='0' or @sub='1' or @sub='2' or @sub='3' or @sub='4' or @sub='5' or @sub='6' or @sub='7' or @sub='8' or @sub='9')
break

set @index =@index + 1
if(@index-1=len(@name))
break

set @sub=substring(@name,@index,1)
end

return substring(@name,1,@index-1)
end


;with t as
(
select id,name,(select count(1) from [testx1] a where a.id<=b.id and dbo.fn_split(a.name)=dbo.fn_split(b.name)) number from [testx1] b
)

update t set name=dbo.fn_split(name)+convert(varchar(20),number-1) where number<>1


你没给出更新的规则,这是最简单的更新了
因为如果有A,A,A1,A1,A2,A2这咋弄?凌乱
A,A3,A1,A4,A2,A5?
还不如A,A1,A2,A3,A4,A5呢
否则就只用游标,如果数据量比较大,估计会慢死人的