日期:2014-05-18  浏览次数:20487 次

同表中记录位置移动问题?求解
问题描述:
例如数据库有一表test中   有字段:ID   user   address
表现在WEB页面时读出记录为:

姓名   地址   操作
————————————————————
张三   张三家   【编辑】=ID(传递ID用于操作)

李四   李四家   【编辑】

王五   王五家   【编辑】
————————————————————

现在【编辑】李四这条记录,选择操作【将其移到张三之前】编辑完之后,刷新页面WEB显示为:

姓名   地址   操作
————————————————————
李四   李四家   【编辑】

张三   张三家   【编辑】

王五   王五家   【编辑】
————————————————————

问题是在数据库中如何操作记录比较合理,意思就是将李四移动到张三之前,其它记录的位置不变。这个过程用SQL语句怎么实现,需要另添加其它字段来控制么?


知道的给指导下,先谢谢了。

------解决方案--------------------
明白了,这样就好了

drop table #A
create table #A (A int,B varchar(50))
insert #A
select 1, 'a ' union all
select 2, 'b ' union all
select 3, 'c ' union all
select 4, 'd ' union all
select 5, 'e ' union all
select 6, 'f '


declare @t1 int
declare @t2 int
declare @str varchar(50)
set @t1=2
set @t2=4
select @str=B from #A where A=@t2
update #A set A=A+1 from #A where A between @t1 and @t2
update #A set A=@t1 from #A where A=@t2+1 and B=@str


select * from #A order by A

--------------
A B
1 a
2 d
3 b
4 c
5 e
6 f