存储过程中使用游标(在存储过程中遍历表)<sql>

由于一直编码写程序,很少编写数据库代码,所以游标什么的都不太熟悉。

以下为存储过程中使用游标,实现存储过程中遍历表:

if exists(select 1 from sysobjects where id=object_id('proc_table1') and xtype='p') --判断存储过程是否存在
drop procedure proc_table1
go
create procedure proc_table1
as
declare @id int
declare @name varchar(50)
declare cr cursor            ---定义游标
for select id,name from table2  
open cr          --打开游标
fetch  next from cr into @id,@name  --游标前进一行
while(@@FETCH_STATUS=0)       --判断游标执行完毕
begin
       update table1 set name = @name  where  table1_id =@id 
       --...-执行一系列操作
end
close cr  --关闭游标
deallocate cr  --删除游标引用 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值