Username: Password:

使用游标批量更改/填充数据表中的记录值(The Using of Cursor)-数据库专栏,SQL Server
来源:作者: 发布时间:2007-12-25 13:49:06


author:david euler
date: 2004/09/28
email:de_euler-david@yahoo.com.cn

有任何问题,请和我联系:)

数据库测试中,常常需要对数据库中的表进行填充或批量更改数据的操作,能够通过游标来实现对每一个查询记录的操作,通过rand()函数的使用获得随机数,将随机数插入到表中,即可更新或填充数据表。

这里涉及到游标的使用,使用游标大体需要经过以下几个步骤:
1.定义游标:declare cursor
2.打开游标:open cursor
3.取得游标中单个的记录,并将记录中的字段赋值给变量。fetch cursor
   (每取一个值,游标会自动前移)
4.循环读取游标,并对每一个记录进行处理。fetch和fetch next 是等价的。
5.关闭并释放游标,close cursor, deallocate cursor。

下面给出一个批量更改数据库中记录的例子,这个例子把价目表中任何料品的价格用0到100之间的数值更新,原价目表中任何料品的价格都为0,更新之后任何的价格都是0到100之间的随机数:

use guruerp

-- 定义游标mytestcursor:
declare  mytestcursor cursor
for select pgi_itm_code,pgi_listprice from tblpricelistgroupitem 
/*从表中选取两个字段*/
/* 表tblpricelistgroupitem中的字段pgi_itm_code是unique key  */

-- 打开游标mytestcursor:
open mytestcursor

declare @pgi_itm_code char(28)
declare @pgi_listprice float

--fetch取出游标所指的记录,并将记录结果存入到变量中:
fetch from mytestcursor into @pgi_itm_code,@pgi_listprice


/*****************  begin of loop *******************************/
while @@fetch_status = 0
begin 
update tblpricelistgroupitem set pgi_listprice=floor(100*rand()) where pgi_itm_code=@pgi_itm_code
fetch next from mytestcursor into @pgi_itm_code,@pgi_listprice
end   
/*****************  end of loop *******************************/

select  @pgi_itm_code as code ,@pgi_listprice as price

/***********关闭游标,释放游标:***************/
close mytestcursor
deallocate mytestcursor

再重复一下,使用游标批量更改或填充数据库,大体经过declare,open,fetch,loop fetch,close and deallocate 五个步骤。

备注1:
       while循环体以begin开始,以end结束,当条件为真时循环继续,为假则结束
备注2:
       @@fetch_status是sql server中的一个变量,下面是sql  server books online上的解释:

returns the status of the last cursor fetch statement issued against any cursor currently opened by the connection.

return valuedescription0fetch statement was successful.-1fetch statement failed or the row was beyond the result set.-2row fetched is missing.
examples
this example uses @@fetch_status to control cursor activities in a while loop.

declare employee_cursor cursor forselect lastname, firstname from northwind.dbo.employeesopen employee_cursorfetch next from employee_cursorwhile @@fetch_status = 0begin fetch next from employee_cursorendclose employee_cursordeallocate employee_cursor

喜欢本文,那就收藏到:

    Del.icio.us Google书签 Digg Live Bookmark Technorati Furl Yahoo书签 Facebook 百度搜藏 新浪ViVi 365Key网摘 天极网摘 和讯网摘 博拉网 POCO网摘 添加到饭否 QQ书签 Digbuzz我挖网
相关评论  我也要评论
还没有关于此文章的相关评论!
  • 昵称: (为空则显示guest)
  • 评论分数: ★ ★ ★★★ ★★★★ ★★★★★
  • 评论内容:(不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
  • 导航
    赞助商
    文章类别
    订阅