--The data cursor acts as a bookmark in the database, which allows an abstract member to be instantiated as an exact object. The cursor is good, but can not be used multiple times, the operation efficiency will be reduced!
use [Database name]GOCreate procedure [dbo].[proc_gitcontent]//Stored Procedure name asDeclare --declaring variables (for inserting data)@content varchar(Max),@sendsuccesscount int,@sendfailecount int,@submitfailcount int,@unknown int,@status int,@userid int,@addtime datetime--defines a cursor (equivalent to a bookmark)DeclareContent_cursorcursor for SelectContent,userid fromTbl_sms_logGroup byContent,useridDeclare @sum intSet @sum=0Create Table#Table([ID] int Identity(1,1)Primary Key not NULL,[Userid] int NULL,--User ID[content] [varchar](Max)NULL,--content[sendsuccess] [int] NULL,--Send success Ten[Sendfail] [int] NULL,--Send failed[Submitfail] [int] NULL,--Commit failed 2[Unknown] [int] NULL,--Unknown 0[Addtime] [datetime] NULL--Add Time)--Open CursorOpenContent_cursor--read cursor (traverse Assignment) (fix duplicate insert bug) Fetch Next fromContent_cursor into @content,@userid while @ @FETCH_STATUS=0 --returns the cursor execution state (0 indicates a successful return result) begin --Send Success Assignment Set @sendsuccesscount=(Select COUNT([Status]) fromTbl_sms_logwhereStatus='Ten' andContent=@content andUserid=@userid Group byContent,userid,[Status]) --Send failed Assignment Set @sendfailecount=(Select COUNT([Status]) fromTbl_sms_logwhereStatus=' -' andContent=@content andUserid=@userid Group byContent,userid,[Status]) --Commit failed Assignment Set @submitfailcount=(Select COUNT([Status]) fromTbl_sms_logwhereStatus='2' andContent=@content andUserid=@userid Group byContent,userid,[Status]) --Unknown Assignment Set @unknown=(Select COUNT([Status]) fromTbl_sms_logwhereStatus='0' andContent=@content andUserid=@userid Group byContent,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 fromContent_cursor into @content,@userid--The cursor is assigned again to resolve the bug that the data is repeatedly inserted End--Close cursor (decalre content_cursor cursor for)CloseContent_cursor--Freeing ResourcesdeallocateContent_cursorbeginSelect * from#Table--Close CursorsEnd
Remember an instance of a database cursor