游标嵌套使用

smile_l 2003-09-29 06:19:37
我想在两个表里对相对应行作比较,想用两个游标,能让这两个游标同时指向下一条记录么,会不会搞混,如果可以请给个简单例子
...全文
46 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
killxtt 2003-09-30
  • 打赏
  • 举报
回复
游标的效率好像很不怎么样吧,如果嵌套估计更够呛
yown 2003-09-30
  • 打赏
  • 举报
回复

试试下面代码,自己将表名、列名改改,特别要注意循环前的语句,记住喽


declare Msg_cursor cursor for
select msg_id,msg from table1
open Msg_cursor
Fetch Msg_cursor into @msg_id,@msg
While (@@Fetch_status=0)
begin
select @Msg_c=@Msg_c+1

select @user_cc=0
declare orderuser_cursor cursor for
select src_id from table2
open orderuser_cursor
Fetch orderuser_cursor into @src_id
while (@@Fetch_status=0)
begin
select @Fee_addr=@src_id,@user_c=@user_c+1,@user_cc=@user_cc+1 --当前记录的用户数,总用户
if exists(select * from smssystem.dbo.tbl_free_user where Src_id=@Src_id) --特权用户
begin
select @Code_scheme=0x8, @userdata_type=0x0,@Fee_user_type=0x0,
@Fee_type='02',@status_rpt=0x1
print 'send Freeuser'
insert into smssystem.dbo.SMS_Send(Src_id,Dest_id,Send_content,Code_scheme,Userdata_type,Service_type,Fee_User_type,Fee_type,Fee_addr,Fee_code,Status_rpt,Dest_addrs)
values(@Dest_id,@Src_id,@msg,@Code_scheme,@userdata_type,@appid,@Fee_user_type,@Fee_type,@Fee_addr,'000000',@status_rpt,@Dest_id)
print '免费:ServiceID:'+@Src_id+' USer:'+@Dest_id+' Msg:'+@msg
end
else -------------定制用户
begin
select @Code_scheme=0x8, @userdata_type=0x0,@Fee_user_type=0x0,
@Fee_type='03',@status_rpt=0x2
print 'Send orderuser'
insert into smssystem.dbo.SMS_Send(Src_id,Dest_id,Send_content,Code_scheme,Userdata_type,Service_type,Fee_User_type,Fee_type,Fee_addr,Fee_code,Status_rpt,Dest_addrs)
values(@Dest_id,@Src_id,@msg,@Code_scheme,@userdata_type,@appid,@Fee_user_type,@Fee_type,@Fee_addr,@Fee_code,@status_rpt,@Dest_id)
print '计费:ServiceID:'+@Src_id+' USer:'+@Dest_id+' Msg:'+@msg
end

--更新操作表
--print '更新'+convert(char(4),@user_c)
update sms.dbo.tbl_Send_msg set send_time=getdate(),send_num=@user_c,send_status=send_status+1,signed_name=signed_name+'-S:'+@user,sended=1
where app_id=@appid and signed_name=@user and sended=0




Fetch next from orderuser_cursor into @src_id
end
close orderuser_cursor
DEALLOCATE orderuser_cursor
Fetch next from Msg_cursor into @msg_id,@msg
end
close Msg_cursor
DEALLOCATE Msg_cursor
end
else
select @result='当前业务没有定制用户!'

end
lvcheng606717 2003-09-30
  • 打赏
  • 举报
回复
你要比较得出什么结果呢,最好用连接,游标是最慢的。
smile_l 2003-09-29
  • 打赏
  • 举报
回复
唔唔,我现在就在出问题阿。。。我们头说,老用select不好,会让程序变慢,我才想用游标,其实很不会用地说,现在一执行就是死循环,哇~~~我要回家啦
sdhdy 2003-09-29
  • 打赏
  • 举报
回复
最好别用游标嵌套,很容易出问题的。

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧