/****** Object: StoredProcedure [dbo].[Proc_GetMealReport] Script Date: 02/14/2013 15:31:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec Proc_GetMealReport 10,2012
ALTER PROCEDURE [dbo].[Proc_GetMealReport](
@MonthId INT,
@pYear INT)
AS
BEGIN
DECLARE @days INT, @daylist VARCHAR(MAX),@MealPrice INT, @daycollist varchar(max), @daysumlist varchar(max),@SubsidyPrice INT
/*set @MonthId = 9
set @pYear = 2012*/
SELECT @days = DAY(DATEADD(D,-1, DATEADD(m,1, CAST(cast(@pYear*100+@MonthId as varchar)+'01' as date))))
;with ctedays as (
select 1 as dd
union all
select dd+1 from ctedays where dd<@days
)
select * into #days from ctedays
select @daylist = stuff((select ',[' + cast(dd as varchar) + ']' from #days for xml path('')),1,1,'')
select @daycollist = stuff((select ',ISNULL([' + cast(dd as varchar) + '],0) AS ['+ cast(dd as varchar)+ ']'
from #days for xml path('')),1,1,'')
select @daysumlist = stuff((select '+ISNULL([' + cast(dd as varchar) + '],0)' from #days for xml path('')),1,1,'')
Select @MealPrice =(SELECT PRICE FROM PriceMaster WHERE Active=1)
Select @SubsidyPrice =(SELECT Subsidy FROM PriceMaster WHERE Active=1)
DECLARE @QUERY NVARCHAR(MAX)
SET @QUERY = 'select ROW_NUMBER() OVER (ORDER BY username) As [S.No.], UserID ,
UserName AS [User Name],' + @daycollist + ',' + @daysumlist+ 'AS [Total Meal],(' + @daysumlist + ')*'
+Convert(VARCHAR(10),@MealPrice-@SubsidyPrice)+' AS [Total Price]
from (
select dd, u.UserId,(u.FirstName+'' ''+u.LastName) AS UserName,isnull((self+Client),0) AS tot,0 as [Total Meal],0 AS [Total Price]
from #days
left join BookingDetails bd on dd = DAY(mealdate)
and YEAR(mealdate)= ' + CAST(@pYear as varchar) + ' and MONTH(mealdate) = '
+ cast(@MonthId as varchar) + '
JOIN Users u
ON
u.UserID=bd.UserID
) src pivot(Min(tot) for dd in(' + @daylist + ')) pvt ORDER BY [User Name]'
print @QUERY
EXEC (@QUERY)
drop table #days
END
No comments:
Post a Comment