日期:2014-05-19  浏览次数:20558 次

sql server随行递增的数据
我的数据表中已经有数据了
现在要在一个字段中生成随列递增的数据
该怎么实现?

table1
xuehao     xingming   xuhao
200701       name1       <null>
200702       name2       <null>
我想在对数据进行增删以后
最后确认的时候表中数据是这样的

xuehao     xingming   xuhao
200701       name1       1
200702       name2       2

谢谢


------解决方案--------------------
select id=identity(int,1,1) , * into test from tb

select * from test

update tb
set xuhao = test.id
from tb , test
where tb.xuehao = test.xuehao and tb.xingming = test.xingming
------解决方案--------------------
如果已存在:
alter table 表名 drop column xuhao--删了再新增

如果只是更新
declare @i int
set @i=0
update 表名
set xuhao=@i,@i=@i+1

------解决方案--------------------
--如果表中數據是這樣的規律的話,也可以不用自增列或者在表上加列,可以直接用一個查詢完成

Select
*,
(Select Count(*) From table1 Where xuehao <= A.xuehao) As xuhao
From
table1 A
------解决方案--------------------


declare @i int

set @i=0

update 表名 set 字段名=@i,@i=@i+1

------解决方案--------------------

create table #t(xuehao varchar(100), xingming varchar(100), xuhao varchar(100))

insert into #t select '200701 ', 'name1 ',null
insert into #t select '200702 ', 'name2 ',null


declare @i int

set @i=0

--用一个update语句即可生成序号列
update #t set xuhao=@i,@i=@i+1


select * from #t


drop table #t


/*
--结果

200701 name1 1
200702 name2 2


*/
------解决方案--------------------
游标轻松实现:

declare cur_1 cursor
for
select xuehao from table1
open cur_1
declare @xuehao varchar
declare @xuhao int
set @xuhao = 1
fetch next from cur_1 into @xuehao
while @@fetch_status = 0
begin
update table1
set xuhao = @xuhao
where xuehao = @xuehao
set @xuhao = @xuhao + 1
fetch next from cur_1 into @xuehao
end

close cur_1
deallocate cur_1