读书人

sql server随行递增的数据,该如何解决

发布时间: 2012-01-07 21:41:55 作者: rapoo

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

读书人网 >SQL Server

热点推荐