双重游标的使用以及动态游标的使用

今天天有个网友 让我写这样一个过程给他
个人表信息表结构:
家庭编码 个人名字 个人编号
312344 刘海源
312344 孔祥玉
312345 梁永胜
312345 高少芝
说明:
4 条个人信息中 由 家庭编码相同的为一个家庭 上面是有2个家庭 每个家庭有2个人
比如: 刘海源 和 孔祥玉 有相同的家庭编码 说明他们同属一个家庭
“个人编号” 字段 是存放 个人在家庭中的编号,有约束为:同一家庭的个人编号不能重复
比如:如果刘海源的个人编号是1 孔祥玉 的个人编号也是1 就违反这个约束了。

需求: 给字段 “个人编号” 赋值 用其标记 在家庭中的编号
注:想要一个 游标 首先 查询出一个结果集 存放“家庭编码”相同的记录,
然后 在结果集里循环 给“个人编号”赋值 如: 1 2 3 4 5 之类
想要的结果:
家庭编码 个人名字 个人编号
312344 刘海源 1
312344 孔祥玉 2
312345 梁永胜 1
312345 高少芝 2

解决方案方案二
declare my_cursor cursor scroll dynamic
for
select 家庭编码 from TEST2 order by 家庭编码 asc
open my_cursor
declare @next_code nvarchar(10)
declare @cur_code nvarchar(10)
while 1=1
begin
fetch my_cursor into @cur_code
if @@fetch_status<>0
break
begin

fetch next from my_cursor into @cur_code
declare @pro_name as nvarchar(10),@cur_name as nvarchar(10)
Declare Code cursor scroll dynamic
FOR SELECT 家庭编码,个人名字 from TEST2 where 家庭编码=@next_code
Open Code
declare @RowCount integer,@i integer
set @i=1
set @RowCount=@@CURSOR_ROWS
while 1=1
begin
fetch Code into
@cur_code,
@cur_name
if @@fetch_status<>0
break
update TEST2 set 个人编号=@i where current of Code
set @i=@i+1
end
close Code
deallocate Code
set @i=1
end
end
close my_cursor
deallocate my_cursor
方案二
declare my_cursor cursor
for
select distinct 家庭编码 FROM TEST2 order by 家庭编码 asc
open my_cursor
declare @cur_name as nvarchar(10),@cur_code nvarchar(10)
while 1=1
begin
fetch my_cursor into @cur_code
if @@fetch_status<>0
break
begin
Declare Code cursor local
FOR SELECT 家庭编码,个人名字 from TEST2 where 家庭编码=@cur_code
Open Code
declare @RowCount integer,@i integer
set @i=1
while 1=1
begin
fetch Code into
@cur_code,
@cur_name
if @@fetch_status<>0
break
update TEST2 set 个人编号=@i where current of Code
set @i=@i+1
end
close Code
deallocate Code
set @i=1
end
end
close my_cursor
deallocate my_cursor

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值