ALTER Proc [dbo].[p_GetServerDataCursor] AS BEGIN IF EXISTS ( SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[#ttableName]') AND type IN ( N'U' ) ) BEGIN DROP TABLE [dbo].[#ttableName] END IF EXISTS ( SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[#tmpReturnData]') AND type IN ( N'U' ) ) BEGIN DROP TABLE [dbo].[#tmpReturnData] END declare @orderNum varchar(255) --建立臨時表存儲tagId create table #ttableName(id int identity(1,1),Orders varchar(255)) --建立臨時表返回數據 create table #tmpReturnData(id int identity(1,1),openid varchar(100),tagid varchar(100)) --定義循環變量,行數,總數 declare @n int,@rows int,@count varchar(1000),@a varchar(100) --查詢去重複tagId插入ttableName中 insert #ttableName(orders) select distinct tagId from Log_TagIdRecord where openId !='null' and IsServer=0 --row獲取tagid行數 rowcount 返回受上一語句影響的行數。若是行數大於20 億,請使用ROWCOUNT_BIG。 select @rows =@@rowcount set @n=1 while @n<=@rows begin --@count查詢數量根據,ttableName表ID自增加根據@n循環每行數據 select @count=COUNT( distinct openId) from Log_TagIdRecord where tagId=(select Orders from #ttableName where id=@n) and openId !='null'and IsServer=0; select @a=Orders from #ttableName where id=@n; IF(@count>49) BEGIN insert #tmpReturnData select distinct top 50 openId,tagId from Log_TagIdRecord where tagId=(select Orders from #ttableName where id=@n) and openId !='null'and IsServer=0; update Log_TagIdRecord set IsServer=1 where openId in (select openid from #tmpReturnData) and tagId in (select tagid from #tmpReturnData) break; END --@n增長 select @n=@n+1 end set @a='select * from #tmpReturnData' EXEC (@a) drop table #ttableName drop table #tmpReturnData END