您的位置:首页 > 其它

利用存储过程把两个表的数据插入到一个新表中(存储过程中写两个游标)

2013-12-11 16:32 676 查看
CREATE PROCEDURE [dbo].[GetAllStuClickTime]

@stime nvarchar(20),--开始时间

@etime nvarchar(20)--结束时间

--时间为第一个循环体 以这个时间段为范围

AS

BEGIN

declare @days int

declare @datediff int

declare @datetime datetime

declare @count INT

declare @classID nvarchar(50)

declare @people nvarchar(20)--学生卡号

declare @type nvarchar(50)--打卡类型

declare @typeValue nvarchar(50)--打卡类型Value值

set datefirst 1

set @count = 0

set @days = 0

set @datediff = datediff(day,@stime,@etime)

while @days <= @datediff --为天数(第几天第几天)

begin

set @datetime = dateadd(day,@days,@stime)

--第二个循环取出学生表中的学生姓名,班级编号

--新建游标

declare StuClickTime cursor for select ClassName,TTCard from dbo.vw_StudentInfo

--打开游标

open StuClickTime

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

fetch next from StuClickTime into @classID,@people

begin

--判断游标的状态

-- 0 fetch语句成功

-- -1 fetch语句失败或此行不在结果集中

-- -2被提取的行不存在

while @@fetch_status = 0

begin

--第三个循环体,将每个学生的每个类型循环

--新建游标

declare StuClickTimeTyp cursor for select PBC_Name,PBC_Value from TB_Code where PBC_Node=48

--打开游标

open StuClickTimeTyp

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

fetch next from StuClickTimeTyp into @type,@typeValue

begin

--判断游标的状态

-- 0 fetch语句成功

-- -1 fetch语句失败或此行不在结果集中

-- -2被提取的行不存在

while @@fetch_status = 0

begin

--判断新表中是否存在此条循环出来的数据

set @count = (select isnull(count(*),0) from dbo.Sm_CheckInout where UserID=@people and resultType=@type and ClockTime=@datetime )

if(@count = 0)

begin

insert into Sm_CheckInout(ClassID,UserID,resultType,ClockTime,resultTypeValue) values(@classID,@people,@type,@datetime,@typeValue)

end

--用游标去取下一条记录

fetch next from StuClickTimeTyp into @type,@typeValue

end

end

--关闭游标

close StuClickTimeTyp

--撤销游标

deallocate StuClickTimeTyp

--用游标去取下一条记录

fetch next from StuClickTime into @classID,@people

end

end

--关闭游标

close StuClickTime

--撤销游标

deallocate StuClickTime

set @days = @days + 1 --循环完了一天然后加一

end

END
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: