日期:2014-05-16  浏览次数:20465 次

简单使用游标插入数据

--创建数据库

create proc InsertStudent

as

--定义所需要的变量

declare @SchoolID int
declare @ClassID int
declare @StudentID int
declare @IDNumber int  --条件判断时需要

begin

--创建游标

declare FeeInsertStudent cursor for 
select stuID,SchID,ClasID from T_School 

--打开游标

open FeeInsertStudent 

--从游标里取出数据给 变量 赋值

fetch next from FeeInsertStudent into @SchoolID,@ClassID,@StudentID

--判断有标的状态

while @@FETCH_STATUS=0

begin

--为变量赋值

set @IDNumber=(select count(*) from T_LeaveSchool where StudentID=@StudentID and SchoolID=@SchoolID and ClassId=@ClassID)
if(@IDNumber=0)  --判断
begin
insert into T_LeaveSchool(StudentID,ClassID,SchoolID)
values( @StudentID,@ClassID,@StudentID)
end
fetch  next from FeeInsertStudent into @SchoolID,@ClassID,@StudentID
end
close FeeInsertStudent         --关闭游标
deallocate FeeInsertStudent                 --撤销游标


end