SQL statement Dual Loop, SQL statement
The shunxu field in Table j_wenzhang_aps201503 is null. Now you want to update the shunxu Field Based on lanmu_id and qishiye.
1. If the shunxu field is auto-incremented, there are no duplicates, And the lanmu_id is small, the shunxu is also small; the lanmu_id is the same, the qishiye is small, and the shunxu is small.
declare @maxid int declare @minid intdeclare @shunxu intdeclare @maxqishiye intdeclare @minqishiye intselect @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=0if ((@maxid is not null) and (@minid is not null))beginwhile (@maxid>=@minid) beginselect @maxqishiye=max(qishiye) from j_wenzhang_aps201503 where shunxu is null and lanmu_id=@minidselect @minqishiye=min(qishiye) from j_wenzhang_aps201503 where shunxu is null and lanmu_id=@minidif ((@maxqishiye is not null) and (@minqishiye is not null))beginwhile (@maxqishiye>=@minqishiye) beginselect @shunxu=@shunxu+1update j_wenzhang_aps201503 set shunxu=@shunxu where lanmu_id=@minid and qishiye=@minqishiye and shunxu is nullselect @minqishiye=min(qishiye) from j_wenzhang_aps201503 where shunxu is null and lanmu_id=@minidendendselect @minid=min(lanmu_id) from j_wenzhang_aps201503 where shunxu is null endendgo
Result After execution:
2. If the shunxu field is auto-incrementing according to the column, and the lanmu_id is small, the shunxu is also small; the lanmu_id is the same, the qishiye is small, and the shunxu is small.
That is, (shunxu increases from 1 in each lanm_id)
declare @maxid int declare @minid intdeclare @shunxu intdeclare @maxqishiye intdeclare @minqishiye intselect @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))beginwhile (@maxid>=@minid) beginselect @maxqishiye=max(qishiye) from j_wenzhang_aps201503 where shunxu is null and lanmu_id=@minidselect @minqishiye=min(qishiye) from j_wenzhang_aps201503 where shunxu is null and lanmu_id=@minidselect @shunxu=0if ((@maxqishiye is not null) and (@minqishiye is not null))beginwhile (@maxqishiye>=@minqishiye) beginselect @shunxu=@shunxu+1update j_wenzhang_aps201503 set shunxu=@shunxu where lanmu_id=@minid and qishiye=@minqishiye and shunxu is nullselect @minqishiye=min(qishiye) from j_wenzhang_aps201503 where shunxu is null and lanmu_id=@minidendendselect @minid=min(lanmu_id) from j_wenzhang_aps201503 where shunxu is null endendgo
Result After execution: