设为首页 加入收藏

TOP

sql语句双重循环
2015-07-24 10:40:24 来源: 作者: 【 】 浏览:1
Tags:sql 语句 双重 循环

\

表 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


执行后结果:


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇SQLServer,仅当使用了列列表并且I.. 下一篇mybatis执行查询语句,可以在plsq..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·About - Redis (2025-12-26 08:20:56)
·Redis: A Comprehens (2025-12-26 08:20:53)
·Redis - The Real-ti (2025-12-26 08:20:50)
·Bash 脚本教程——Li (2025-12-26 07:53:35)
·实战篇!Linux shell (2025-12-26 07:53:32)