在数据库中经常有Version这个选项,如果Version乱了.要更新往往要用到游标.但游标效率比较慢.下边就介绍一种比较快捷的不用游标的方法:
update version
select * into #a from (
select 1 as ID,1 as PID,1 as Ver
union select 2, 1, 1
union select 3, 1, 1
union select 4, 2, 1
union select 5, 2, 1
union select 6, 3, 1
union select 7, 3, 1
union select 8, 3, 5
) a
select ID,PID,(select Count(*) from #a where PID=a.PID and ID<=a.ID) as Ver into #b from #a a
update #a set Ver=b.Ver from #b b where #a.ID=b.ID and #a.PID=b.PID
select * from #a
drop table #a
drop table #b
select * into #a from (
select 1 as ID,1 as PID,1 as Ver
union select 2, 1, 1
union select 3, 1, 1
union select 4, 2, 1
union select 5, 2, 1
union select 6, 3, 1
union select 7, 3, 1
union select 8, 3, 5
) a
select ID,PID,(select Count(*) from #a where PID=a.PID and ID<=a.ID) as Ver into #b from #a a
update #a set Ver=b.Ver from #b b where #a.ID=b.ID and #a.PID=b.PID
select * from #a
drop table #a
drop table #b
甚至不用临时表:
update2
select * into #a from (
select 1 as ID,1 as PID,1 as Ver
union select 2, 1, 1
union select 3, 1, 1
union select 4, 2, 1
union select 5, 2, 1
union select 6, 3, 1
union select 7, 3, 1
union select 8, 3, 5
) a
update #a set Ver=(select Count(*) from #a where PID=b.PID and ID<=b.ID) from #a b
select * from #a
drop table #a
select * into #a from (
select 1 as ID,1 as PID,1 as Ver
union select 2, 1, 1
union select 3, 1, 1
union select 4, 2, 1
union select 5, 2, 1
union select 6, 3, 1
union select 7, 3, 1
union select 8, 3, 5
) a
update #a set Ver=(select Count(*) from #a where PID=b.PID and ID<=b.ID) from #a b
select * from #a
drop table #a