数据库 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