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

本文介绍了一个存储过程,该过程通过游标技术将两个表的数据整合并插入到一个新的表中。首先设置日期变量,然后通过游标遍历学生表,判断新表中是否存在相同记录,如果不存在则进行插入操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值