I need help building a loop in my stored procedure, basically i want it too loop from 2005 till the current year.
ALTER PROCEDURE [dbo].[testt1]
as
DECLARE @YearToGet int;
SET @YearToGet = 2005;
WITH Years AS (
SELECT DATEPART(year, GETDATE()) [Year]
UNION ALL
SELECT [Year]-1 FROM Years WHERE [Year]>@YearToGet
)
SELECT TOP (100) PERCENT DIVISION, DYYYY, SUM(APRICE) AS Sales, SUM(PARTY) AS PAX, SUM(NetAmount) AS NetSales, SUM(InsAmount)
AS InsSales, SUM(CancelRevenue) AS CXSales, SUM(OtherAmount) AS OtherSales, SUM(CXVALUE) AS CXValue
FROM dbo.B101BookingsDetails AS B101BookingsDetails
WHERE Booked <= CONVERT(int,DateAdd(year, (SELECT * FROM Years) - Year(getdate()), DateAdd(day, DateDiff(day, 2, getdate()), 0)))
and DYYYY = @YearToGet
GROUP BY DYYYY, DIVISION
ORDER BY DIVISION, DYYYY
OPTION (MAXRECURSION 0) -- this avoids hitting the recursion limit in the CTE
and i could really used a stored procedure website that goes into more detail then just the simple select statements
YEAR(GETDATE())instead of the oddball DATENAME() approach..... also: you're never updating your@YearToGetoryearvalue - I would think this ends in either a non-loop or an endless loop....