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

这个需求用SQL语句能实现吗?
表a如下:


ID     组序           类型
------------------
1       1/3             广告
2       2/3             广告
3       3/3             广告
4       0                 节目
5       1/4             广告
6       2/4             广告          
7       3/4             广告
8       4/4             广告
9       0                 节目


例1:如果删除ID=2的数据时,组序字段要重新计算结果应该如下:

ID     组序           类型
------------------
1       1/2             广告
3       2/2             广告
4       0                 节目
5       1/4             广告
6       2/4             广告          
7       3/4             广告
8       4/4             广告
9       0                 节目

例2:如果删除ID=2和ID=7的数据时,组序字段要重新计算结果应该如下:

ID     组序           类型
------------------
1       1/2             广告
3       2/2             广告
4       0                 节目
5       1/3             广告
6       2/3             广告          
8       3/3             广告
9       0                 节目

------解决方案--------------------
update tt1 set
zx = str((select count(*) from tt1 z
where right(tt1.zx,len(tt1.zx)-charindex( '/ ',tt1.zx))=
right( z.zx,len( z.zx)-charindex( '/ ', z.zx))
and cast(left( z.zx,charindex( '/ ', z.zx)-1) as int) <=
cast(left(tt1.zx,charindex( '/ ',tt1.zx)-1) as int)
))+right(tt1.zx,len(tt1.zx)-charindex( '/ ',tt1.zx))

呵呵,不过我还是建议你把组序和组号分成两个数字字段,免得这么麻烦
如果你实在懒得优化,那就用触发器,效果应该比写SQL语句强
------解决方案--------------------
你要知道即便是 delete ... 2 and 7 and 8....時 他也是一個一個刪的所以有下面的
create trigger trg_a on a
for delete
as
begin
select top 1 @id1 = ID from a where 組序 = 0 and ID < deleted.ID order by ID desc
select top 1 @id2 = ID from a where 組序 = 0 and ID > deleted.ID oder by ID
select @icount count(ID) from a where ID between @id1 and @id2
select @fz = (case ID )
update a set 組序 = (case when ID < @deleted.ID then SubString(組序,1,2) + @icount
else cast(int,SubString(