Update的简单问题(解决马上给分)
表 中数据如下
id name
1 a
3 b
3 b
3 b
3 b
3 b
4 7
我想得到结果是
id name
1 a
3 b
5 b
7 b
9 b
11 b
13 7
ID 的差值为2
怎么写这个语句 , 记得可以用update来完成
------解决方案--------------------没人弄,我来献丑了.不会用游标....第一次用.一点思路,见笑
create table tb (
[id1] [int] IDENTITY (1, 1) NOT NULL ,
[id] int,
[name] char
)
go
insert into tb
select 1 , 'a '
union
select 3 , 'b '
union
select 5 , 'b '
union
select 7 , 'b '
union
select 9 , 'b '
union
select 11 , 'b '
union
select 13 , '7 '
go
declare @ss int
declare @s int
declare @sss int
declare @a int
select @ss=1
select @sss=1
select @a=1
select @s=count(1) from tb
DECLARE testcusor CURSOR FOR
select * from tb where id1=@a
OPEN testcusor
FETCH NEXT FROM testcusor
WHILE @@FETCH_STATUS = 0
BEGIN
while @a <=@s
begin
FETCH NEXT FROM testcusor
update tb set id=@ss where id1=@a
set @ss=@ss+2
set @a=@a+1
end
END
CLOSE testcusor
DEALLOCATE testcusor
GO
----
1 1 a
2 3 b
3 5 b
4 7 b
5 9 b
6 11 b
7 13 7
------解决方案-------------------- create table #t(id int, name varchar(100))
insert into #t
select 1, 'a ' union all
select 3, 'b ' union all
select 3, 'b ' union all
select 3, 'b ' union all
select 3, 'b ' union all
select 3, 'b ' union all
select 4, '7 '
select * from #t
--以下update更新即可
declare @i int
set @i =-1
update #t set id=@i,@i=@i+2
select * from #t
drop table #t