您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

sql中存储过程和游标简单示例

2024/7/19 11:36:08发布30次查看
本文章综合的讲述了关于sql中游标和存储过程的二种实现方法,有需要学习这方面内容的人可以参考一下本文章。
 代码如下 复制代码
--创建存储过程 sp_tittles
 if exists(select * from sys.objects where type='p' and name='sp_titles')
    drop proc sp_titles
 go
 create proc sp_titles
 as
     declare @problemid int,@titleid int,@item int
     --声明一个游标
     declare cursor_title cursor for
         select [pid],[id]
         from [tb_titles]
     --打开游标
     open cursor_title
     --提取游标第一行
     fetch next from cursor_title into @problemid,@titleid
     --循环提取游标内容
     while @@fetch_status=0
     begin
         if exists(
             select *
             from [tb_problemindex]
             where [problemid]=@problemid)
             begin
                 select top 1 @item=[id] from [tb_titles] where [pid]=@problemid order by createtime desc
                 update [tb_problemindex] set [titleid] = @item where [problemid]=@problemid
             end
         else
             insert into [tb_problemindex]([problemid],[titleid])
             values(@problemid,@titleid)
         fetch next from cursor_title into @problemid,@titleid
     end
     --关闭游标
     close cursor_title
     --释放游标资源
     deallocate cursor_title
 go
 --存储过程 sp_titles 结束
--执行存储过程 sp_titles
 exec sp_titles
--创建存储过程 sp_answers
 if exists(select * from sys.objects where type='p' and name='sp_answers')
     drop proc sp_answers
 go
 create proc sp_answers
 as
     declare @problemid int,@answerid int
     --声明一个游标
     declare cursor_answer cursor for
         select [pid],[id]
         from [tb_answers]
     --打开游标
     open cursor_answer
     --提取游标第一行内容
     fetch next from cursor_answer into @problemid,@answerid
     --循环提取游标内容
     while @@fetch_status=0
     begin
         update [tb_problemindex] set [answerid]=@answerid where [problemid]=@problemid
         fetch next from cursor_answer into @problemid,@answerid
     end
     --关闭游标
     close cursor_answer
     --释放游标资源
     deallocate cursor_answer
 go
 --存储过程 sp_answers 结束
--执行存储过程 sp_answers
 exec sp_answers
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product