循环update的问题

半职业打酱油 2008-06-16 11:23:26
现在一个表中有N多行数据
需要将其中一个字段(INT)类型的数据更新
将其值更新为从1开始递增,
例如
第一行更新为1
第二行更新为2




第N行更新为N

用SQL如何实现?是否需要游标!麻烦给出代码,3KS!
...全文
245 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
tianyusunkuangyu 2008-06-16
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 perfectaction 的回复:]
借助临时表:

SQL codecreate table T(pid int primary key,id int,name varchar(20))
insert into t select 1,4,'a'
insert into t select 2,4,'b'
insert into t select 3,4,'c'
insert into t select 4,43,'d'
insert into t select 5,42,'e'
insert into t select 6,4,'f'

select pid,identity(int,1,1) as id into # from T order by pid
update T set id=b.id from T as a inner join # as b on a.pid=b.pid

[/Quote]

三楼的也可以,就是有点麻烦了
tianyusunkuangyu 2008-06-16
  • 打赏
  • 举报
回复
declare @i int
set @i=0

update T
set COl1=@i,@i=@i+1
muzhenxing013 2008-06-16
  • 打赏
  • 举报
回复
-------------如果一行一行的操作最好用用表


declare @aa int
set @aa=1
declare ppp_10002 cursor for
select contract from authors
open ppp_10002
fetch next from ppp_10002
while(@@fetch_status=0)

fetch next from ppp_10002
begin
set @aa=@aa+1
update authors set contract=@aa where current of ppp_10002

end
nzperfect 2008-06-16
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 roy_88 的回复:]
declare @i int
set @i=0

update T
set COl1=@i,@i=@i+1
[/Quote]

太聪明了。。学习
nzperfect 2008-06-16
  • 打赏
  • 举报
回复
借助临时表:
create table T(pid int primary key,id int,name varchar(20))
insert into t select 1,4,'a'
insert into t select 2,4,'b'
insert into t select 3,4,'c'
insert into t select 4,43,'d'
insert into t select 5,42,'e'
insert into t select 6,4,'f'

select pid,identity(int,1,1) as id into # from T order by pid
update T set id=b.id from T as a inner join # as b on a.pid=b.pid

select * from t
/*
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
6 6 f
*/
中国风 2008-06-16
  • 打赏
  • 举报
回复
declare @i int
set @i=0

update T
set COl1=@i,@i=@i+1
liangCK 2008-06-16
  • 打赏
  • 举报
回复
declare @i int
set @i=1
update tb
set 字段int=@i,
@i=@i+1
半职业打酱油 2008-06-16
  • 打赏
  • 举报
回复
学习了,回去研究研究!
最开始本来是想用.NET写程序实现的
但是发现不好获取需要更新的行的索引,也能实现但是麻烦
而t-sql又不熟悉]
3KS!

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧