使用游標批量更改/填充數據表中的記錄值(The Using of Cursor)
2024-07-21 02:07:28
供稿:網友
author:david euler
date: 2004/09/28
email:[email protected]
有任何問題,請與我聯系:)
數據庫測試中,常常需要對數據庫中的表進行填充或者批量更改數據的操作,可以通過游標來實現對每一個查詢記錄的操作,通過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 [email protected]_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