Monday, September 30, 2013

Cursor For Generate Bill Month

USE [ShopSMCity]
GO
/****** Object:  StoredProcedure [dbo].[SP_Advertising_GetBillMonth]    Script Date: 10/01/2013 10:09:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- EXEC SP_Advertising_GetBillMonth  @BillNo='201301260006'
-- =============================================
CREATE PROCEDURE [dbo].[SP_Advertising_GetBillMonth]
(
@BillNo nvarchar(30)
)

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
 

Declare
      @MonthBill nvarchar(15),
      @List nvarchar(300),
      @ID int
     
Create table  #temp(
ID int identity(1,1),
[Month YYYY]  nvarchar(20)
)    
insert into #temp([Month YYYY])    
SELECT (CASE
When [PaymentType]= 'Pre Paid' then DATENAME(MONTH, BillDate) + ' ' + DATENAME(YEAR, BillDate)
Else DATENAME(MONTH,dateadd(d,-1, BillDate)) + ' ' + DATENAME(YEAR, dateadd(d,-1, BillDate))

END)  AS [Month YYYY]
--DATENAME(MONTH, BillDate) + ' ' + DATENAME(YEAR, BillDate) AS [Month YYYY]

from Advertising_BillCreationDetails WHERE BillNo=@BillNo order by  BillDate

--select * from     #temp  


 
 DECLARE cursor_MonthList CURSOR FOR

 SELECT distinct  [Month YYYY],ID from #temp order by ID

 DECLARE @charInx int

 OPEN cursor_MonthList
 FETCH NEXT FROM cursor_MonthList INTO @MonthBill,@ID
 set @List = @MonthBill;
 WHILE @@FETCH_STATUS=0
 BEGIN
   

FETCH NEXT FROM cursor_MonthList INTO @MonthBill,@ID

SET @charInx =0

 select @charInx=  charindex(@MonthBill, @List)

 if(@charInx <=0)
 BEGIN
set @List += +', '+ @MonthBill;
END
 END
 CLOSE cursor_MonthList
 DEALLOCATE cursor_MonthList

 select coalesce(@List,'') as BillMonthList

 drop table #temp

END

No comments:

Post a Comment