SQL SERVER 游标的使用(2)

 

  --对于表
  Create Table BorrowRecord(         --学生借书记录表
    BorrowRecord int identity(1,1),     --流水号 
    StudentID   int ,             --学号
    StudentFeeID int ,           --费用结算号   (外键)
    BorrowDate   datetime,     --借出时间
    ReturnDAte   Datetime,   --归还时间
    Fee       Money               --借书费用 
    
  )

  
Create Table StudentFee(           --学生费用结算表
    StudentFeeID int primarykey ,     --费用结算号   (主键)
    StudentID int ,               --学号
    BorrowBookAllFee       Money,   --所有借书总费用   
    
  )

 
-- 两者关系为多对一的关系,关联字段为StudentFeeID

  
--由于某种原因StudentFee表的数据遭到了破坏,我想StudentFee循环一遍将“所有借书总费用”重算 。

  
-----------------------------------------------------------------------
  -------------------------------------------------------
  --Name:一部分代码
--
func:更新学生借书总费用
--
Use :
  --User:
  --Author: wp_love
  --Date : 2003-4-16
  --Memo : 临时写写的,给大家作个Sample。没有调试阿。
  -------------------------------------------------------

  
--声明一个游标
  Declare curStudentFee Cursor
    
for 
    
Select StudentFeeID From StudentFee     

  
--声明两个费用变量
  Declare @mBorrowBookAllFee Money --总费用
  Declare @iStudentFeeID   Int   --借书结算号

--初始化 
  Set @mBorrowBookAllFee=0
      
Set @iStudentFeeID=0

  
--打开游标
  Open curStudentFee 

  
--循环并提取记录
  Fetch Next From curStudentFee Into @iStudentFeeID   
  
While ( @@Fetch_Status=0 )   
        
begin

    
--从借书记录中计算某一学生的借书总记录的总费用
    Select @mBorrowBookAllFee=Sum(BorrowBookAllFee)
        
From BorrowRecord 
        
Where StudentFeeID=@iStudentFeeID   

    
--更新到汇总表。
    Update StudentFee Set BorrowBookAllFee=@mBorrowBookAllFee
        
Where StudentFeeID=@iStudnetFeeID       

        
Fetch Next From curStudentFee Into @mFee
      
end

  
--关闭游标   
  Close curStudentFee

  
--释放游标
  Deallocate curStudentFee 

 

posted on 2005-10-15 11:24 ffan 阅读(2489) 评论(0)  编辑 收藏 引用 所属分类: 备忘

只有注册用户登录后才能发表评论。
<2005年10月>
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345

导航

统计

常用链接

留言簿(12)

随笔分类

随笔档案

相册

搜索

最新评论

阅读排行榜

评论排行榜