sql使用临时表循环

code

CREATE PROCEDURE sp_Update_Blogger_Blog_ArticleCount
AS
BEGIN
    declare @account varchar(50);   --博主账号
    declare @count int;             --博主数量
    declare @i int;                 --循环标识
    declare @articleCount int;      --文章数量 
    --把所有博主信息存到临时表
    select * into #temp from(select  Account,Ranking,ROW_NUMBER() over(order by Ranking) as row from Blogger ) b
    select @count = COUNT(1) from #temp;
    set @i = 1;
    --循环临时表
    while (@count >= @i)
       begin
          select @account = Account from #temp where row = @i; --获取当前行的博主账号
          select @articleCount = count(1) from BlogForBlogger where Account = @account;  --获取博主的文章数量
          update Blogger set ArticleCount = @articleCount; --更新博主的文章数量
          set @i = @i + 1;
       end
    drop table #temp; --删除临时表
END
GO
原文地址:https://www.cnblogs.com/xsj1989/p/11544860.html