--数据游标在数据库中起到的就是一个书签的作用,它让一个抽象的成员实例化为一个准确的对象。游标虽好,但是可不能多次使用,运行效率会降低! USE [数据库名] GO Create procedure [dbo].[proc_gitcontent]//存储过程名称 as declare --声明变量(用于插入数据) @content varchar(max), @sendsuccesscount int, @sendfailecount int, @submitfailcount int, @unknown int, @status int, @userid int, @addtime datetime --定义一个游标cursor(相当于一个书签) declare content_cursor cursor for select Content,userid from tbl_sms_log group by Content,userid declare @sum int set @sum=0 create table #table ( [ID] int identity(1,1) primary key NOT NULL, [Userid] int null,--用户id [content] [varchar](max) null,--内容 [sendsuccess] [int] null,--发送成功 10 [sendfail] [int] null,--发送失败 20 [submitfail] [int] null,--提交失败 2 [unknown] [int] null,--未知数 0 [addtime] [datetime] null--添加时间 ) --打开游标 open content_cursor --读取游标(遍历赋值)(解决重复插入的bug) fetch next from content_cursor into @content,@userid while @@FETCH_STATUS=0 --返回游标执行状态(0表示返回结果成功) begin --发送成功赋值 set @sendsuccesscount=(select COUNT([status]) from tbl_sms_log where status='10' and Content=@content and UserID=@userid group by Content,userid,[status]) --发送失败赋值 set @sendfailecount=(select COUNT([status]) from tbl_sms_log where status='20' and Content=@content and UserID=@userid group by Content,userid,[status]) --提交失败赋值 set @submitfailcount=(select COUNT([status]) from tbl_sms_log where status='2' and Content=@content and UserID=@userid group by Content,userid,[status]) --未知赋值 set @unknown=(select COUNT([status]) from tbl_sms_log where status='0' and Content=@content and UserID=@userid group by Content,userid,[status]) set @addtime =GETDATE() --set @sum+=1 insert into #table(Userid,content,sendsuccess,sendfail,submitfail,unknown,addtime) values (@userid,@content,@sendsuccesscount,@sendfailecount,@submitfailcount,@unknown,@addtime) fetch next from content_cursor into @content,@userid--游标再次赋值,解决数据重复插入的bug end --关闭游标(decalre content_cursor cursor for) close content_cursor --释放资源 deallocate content_cursor begin select * from #table --关闭游标 end