時間段內月份統計, 查詢結果循環

USE [CommunityApp]
GO
/****** Object:  StoredProcedure [dbo].[sp_count_OwnerPayList]    Script Date: 03/04/2016 11:32:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[sp_count_OwnerPayList]  
 @CommunityIDs int,--如果爲0查出所有的,不爲0則查指定小區
 @FeeName nvarchar(50),
  @StarTime as datetime,--開始時間
 @EndTime as datetime --結束時間
AS
  declare @i int,
    @j int,
   @months nvarchar(50),--當前月
   @FeeMoney decimal(10, 2),
  @CommunityID int,
  @CommunityName nvarchar(50)
 
  
 DECLARE @tCommunity TABLE  --所有的小區
 (  
  CommunityID  int  ,
  CommunityName nvarchar(50)
  ,FlagID   TINYINT    
 ) 
  DECLARE @tYuefen TABLE  --所有的月份
 (  
  months nvarchar(50)
  ,FlagID   TINYINT    
 ) 
 DECLARE @tcount TABLE  
 (  
  CommunityName nvarchar(50),--小區
  Months   nvarchar(100),--月份
  FeeMoney  decimal(10, 2)  --繳費金額
 ) 
 
BEGIN  
--獲得小區 star
IF @CommunityIDs=0
begin
 insert @tCommunity  select CommunityID,CommunityName,0 from CommunityBase.dbo.CommunityList
 end
 else
 begin
  insert @tCommunity  select CommunityID,CommunityName,0 from CommunityBase.dbo.CommunityList where CommunityID=@CommunityIDs
 end
--獲得小區 end

--獲得月份 star

;with t
as
(select @StarTime as y
 union all
 select  dateadd(m,1,y)from t where y <@EndTime)
 insert @tYuefen select  convert(varchar(7),y,120),0 from t
 
 
--獲得月份 end

 
 SET @i=1  
 WHILE( @i>=1)  ---第一次循環star
 BEGIN  
    
  set @CommunityID=''  
   set @CommunityName=''  
  SELECT TOP 1 @CommunityID = CommunityID,@CommunityName = CommunityName FROM @tCommunity  WHERE flagID=0  
  SET @i=@@ROWCOUNT  
    
  IF @i<=0 GOTO Return_Lab  
     
 
 SET @j= 1
 WHILE( @j>=1) ---第二次循環star 
  BEGIN
     SELECT TOP 1 @months = months FROM @tYuefen  WHERE flagID=0  
  SET @j=@@ROWCOUNT  
  IF @j<=0 GOTO Return_Lab2  
  
  

   IF @FeeName=''
begin
   SELECT @FeeMoney=sum(FeeMoney) FROM OwnerPayList WHERE PayMonth=@months  and CommunityID= @CommunityID   --月份的錢
 end
 else
 begin
   SELECT @FeeMoney=sum(FeeMoney) FROM OwnerPayList WHERE PayMonth=@months and FeeName=@FeeName and CommunityID= @CommunityID   --月份的錢
 end
   
 if @FeeMoney is not null
 begin
  insert @tcount values(@CommunityName,@months,@FeeMoney)
  end
  
   IF @@error=0   
      UPDATE @tYuefen SET flagID=1 WHERE months = @months
 
 
  Return_Lab2:    
   end ---第二次循環 end
   
   IF @@error=0   
      UPDATE @tCommunity SET flagID=1 WHERE CommunityID = @CommunityID
       
 Return_Lab:  
 END  ---第一次循環 end
 select * from   @tcount


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章