数据库 SQL Server游标
来源:互联网 发布:nc软件下载 编辑:程序博客网 时间:2024/05/22 14:41
先创建一个table
代码:
<strong>declare cursor1 cursor for --定义游标cursor1select * from dbo.MyTableopen cursor1 --打开游标fetch next from cursor1 --将游标向下移动一条--循环,当@@fetch_status不是0时,停止读取。while @@fetch_status=0 --判断是否成功获取数据begin fetch next from cursor1 --将游标向下移动一条endclose cursor1 --关闭游标deallocate cursor1 --释放资源</strong>
执行结果:
每条数据都有列名等,比较耗费资源。但是当你要一条条的对数据进行操作时,就要用到它了。
比如下面两个表,mytable.id=mycard.pid时,mytable表中的pay要等于pay加上mycard中的paycard
代码如下,执行
declare cursor1 cursor for --定义游标cursor1select pid,paycard from dbo.MyCard --从MyCard 表中读取数据declare @cid int declare @cmoney intopen cursor1 --打开游标fetch next from cursor1 into @cid,@cmoney while @@fetch_status=0 --判断是否成功获取数据begin update dbo.MyTable set pay=pay+@cmoney where id=@cid fetch next from cursor1 into @cid,@cmoney endclose cursor1 --关闭游标deallocate cursor1 --释放资源
查询mytable中结果如下:
我们可以看到id为1和3 的pay已经变为原先pay加上Mycard中paycard的值了。
下面这个就是循环从Yt_Store_StockInTemp 中读取数据,然后和Yt_Store_Inventory
中主键相同的uCount进行比较,在Yt_Store_Inventory 中不存在的或者数量不足的,设置当前行的isvalid=3
declare cursor1 cursor for --定义游标cursor1select attachmentCode,objectState,DID ,userId ,uCount, isvalid from dbo.Yt_Store_StockInTemp where isvalid is null and type=2 and userid=@userId open cursor1 --打开游标fetch next from cursor1 into @attachmentCode, @objectState, @DID ,@User ,@uCount,@isvalid --将游标向下移动一条--循环,当@@fetch_status不是0时,停止读取。while @@fetch_status=0 --判断是否成功获取数据begindeclare @CountFlg intselect @CountFlg=(isnull(uCount,0)-@uCount) from dbo.Yt_Store_Inventory where userId=@User and attachmentCode=@attachmentCode and DID=@DID and objectState=@objectState if @CountFlg<0 or (@CountFlg IS NULL)--库存不足beginupdate dbo.Yt_Store_StockInTemp set isvalid=3 where current of cursor1end fetch next from cursor1 into @attachmentCode, @objectState, @DID ,@User ,@uCount,@isvalid --将游标向下移动一条endclose cursor1 --关闭游标deallocate cursor1 --释放资源
0 0
- 数据库 SQL Server游标
- Sql Server游标和数据库设计
- SQL Server 游标运用:批量备份数据库
- SQL Server 数据库游标的使用
- SQL-SERVER 声明游标
- sql server 游标使用
- SQL-SERVER声明游标
- SQL Server 游标使用方法
- SQL-SERVER 声明游标
- SQL-SERVER 声明游标
- SQL-SERVER声明游标
- SQL SERVER 游标
- Sql Server游标使用
- [SQL Server]游标示例
- SQL SERVER 游标 更新
- SQL Server 游标
- SQL Server 游标
- sql server 游标 例子
- Lua协同程序
- 最后一节php+mysql的故事
- CentOS安装XRDP实现远程桌面访问
- ajax 调用接口 C# 调用接口 PostHttpResponse 类
- android关于监听电话拨打后,对方接听的状态(COLP被连接线识别提示)
- 数据库 SQL Server游标
- Redis基本使用
- C++第3次上机实验-个人所得税计算机
- 建造者模式(C++)
- hdu 5652 India and China Origins 并查集
- nodejs小记之formidable同步图片文件上传
- 4.4.3 single_server_wakeup函数:执行业务模块回调函数
- Django1.6 用Form实现注册登录注销修改密码
- Django1.6 用Form实现注册登录注销修改密码