在開發中,常常會遇到一個場景。須要批量處理數據,循環添加、刪除、修改一些數據。spa
需求:代理
有 文章表(dbo.Gas_Article)、文章做者表(dbo.Gas_ArticleAuthor)code
如今須要在後臺統計出每一個做者共發佈了多少文章,和全部文章閱讀量之和的數據blog
如下是個人處理方案:開發
編寫PROCEDURE,內部利用遊標循環處理數據,而後使用SqlServer代理,新建一個做業定時任務處理,這樣就能夠在後臺實時統計了。it
1 CREATE PROCEDURE Job_UpdateAuthor --建立PROCEDURE 2 AS 3 BEGIN 4 DECLARE UpdateAuthorCursor CURSOR --定義遊標 5 FOR 6 SELECT COUNT(*) AS ArticleNumber , 7 SUM(ShowHits) AS ArticleHits , 8 Author 9 FROM dbo.Gas_Article 10 WHERE Author IN ( SELECT Name 11 FROM dbo.Gas_ArticleAuthor 12 WHERE IsDelete = 0 ) 13 GROUP BY Author --查出須要的數據至遊標中 14 15 OPEN UpdateAuthorCursor --打開遊標 16 17 DECLARE @Number INT, @Hits INT, @Author NVARCHAR(255) 18 FETCH NEXT FROM UpdateAuthorCursor INTO @Number, @Hits, @Author --讀取第一行數據,賦值給變量 19 20 WHILE @@FETCH_STATUS = 0 21 BEGIN 22 UPDATE dbo.Gas_ArticleAuthor 23 SET ArticleNumber = @Number , 24 ArticleHits = @Hits 25 WHERE Name = @Author -- 更新dbo.Gas_ArticleAuthor數據 26 27 FETCH NEXT FROM UpdateAuthorCursor INTO @Number, @Hits, @Author --讀取下一行數據 28 END 29 30 CLOSE UpdateAuthorCursor --關閉遊標 31 32 DEALLOCATE UpdateAuthorCursor --釋放遊標 33 END 34 GO