表 j_wenzhang_aps201503 中 shunxu 字段爲null。現在 想根據 lanmu_id,qishiye兩項,更新shunxu 字段。
1 、如果讓shunxu 字段 自增,不存在重複,且lanmu_id 較小的,對應的 shunxu 也小;lanmu_id 相同,qishiye較小的,對應的shunxu也小。
declare @maxid int
declare @minid int
declare @shunxu int
declare @maxqishiye int
declare @minqishiye int
select @maxid= max(lanmu_id) from j_wenzhang_aps201503 where shunxu is null
select @minid= min(lanmu_id) from j_wenzhang_aps201503 where shunxu is null
select @shunxu=0
if ((@maxid is not null) and (@minid is not null))
begin
while (@maxid>=@minid)
begin
select @maxqishiye=max(qishiye) from j_wenzhang_aps201503 where shunxu is null and lanmu_id=@minid
select @minqishiye=min(qishiye) from j_wenzhang_aps201503 where shunxu is null and lanmu_id=@minid
if ((@maxqishiye is not null) and (@minqishiye is not null))
begin
while (@maxqishiye>=@minqishiye)
begin
select @shunxu=@shunxu+1
update j_wenzhang_aps201503 set shunxu=@shunxu where lanmu_id=@minid and qishiye=@minqishiye and shunxu is null
select @minqishiye=min(qishiye) from j_wenzhang_aps201503 where shunxu is null and lanmu_id=@minid
end
end
select @minid=min(lanmu_id) from j_wenzhang_aps201503 where shunxu is null
end
end
go
執行後結果:
2、如果按照欄目 讓shunxu 字段 自增,且lanmu_id 較小的,對應的 shunxu 也小;lanmu_id 相同,qishiye較小的,對應的shunxu也小。
即(每個相同lanm_id裏,shunxu 都從1 開始增加)
declare @maxid int
declare @minid int
declare @shunxu int
declare @maxqishiye int
declare @minqishiye int
select @maxid= max(lanmu_id) from j_wenzhang_aps201503 where shunxu is null
select @minid= min(lanmu_id) from j_wenzhang_aps201503 where shunxu is null
if ((@maxid is not null) and (@minid is not null))
begin
while (@maxid>=@minid)
begin
select @maxqishiye=max(qishiye) from j_wenzhang_aps201503 where shunxu is null and lanmu_id=@minid
select @minqishiye=min(qishiye) from j_wenzhang_aps201503 where shunxu is null and lanmu_id=@minid
select @shunxu=0
if ((@maxqishiye is not null) and (@minqishiye is not null))
begin
while (@maxqishiye>=@minqishiye)
begin
select @shunxu=@shunxu+1
update j_wenzhang_aps201503 set shunxu=@shunxu where lanmu_id=@minid and qishiye=@minqishiye and shunxu is null
select @minqishiye=min(qishiye) from j_wenzhang_aps201503 where shunxu is null and lanmu_id=@minid
end
end
select @minid=min(lanmu_id) from j_wenzhang_aps201503 where shunxu is null
end
end
go
執行後結果: