国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

使用游標批量更改/填充數據表中的記錄值(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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 石景山区| 叙永县| 都兰县| 临沭县| 明光市| 静安区| 武威市| 青川县| 井冈山市| 望都县| 綦江县| 南木林县| 静安区| 梧州市| 兴仁县| 怀安县| 绥芬河市| 嘉定区| 克东县| 镇雄县| 潞西市| 涪陵区| 竹溪县| 奇台县| 阳朔县| 浑源县| 南丹县| 东丰县| 新兴县| 青河县| 石林| 昌黎县| 仪征市| 四平市| 廊坊市| 苗栗县| 静安区| 凯里市| 灵台县| 手机| 阜南县|