sql存储过程循环

时间:2011-01-04 21:33:25

标签: sql sql-server-2005 stored-procedures

我需要帮助在我的存储过程中构建一个循环,基本上我希望它从2005年到今年也是循环。

 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

我真的可以使用一个存储过程网站,它更详细,然后只是简单的选择语句

3 个答案:

答案 0 :(得分:4)

这不是直接的答案,但代码无法以可读的方式发布在评论中,所以我认为这应该没问题:

不要在SP中循环,而是使用CTE生成所需的数字。

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 * FROM Years -- join here with your query
OPTION (MAXRECURSION 0) -- this avoids hitting the recursion limit in the CTE

修改:试试这个

WITH  Years
          AS (
              SELECT DATEPART(year, GETDATE()) [Year]
              UNION ALL
              SELECT [Year]-1
                FROM Years
                WHERE [Year] > @YearToGet
             )
    SELECT 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 
      JOIN Years yr ON DYYYY = yr.[Year]
      WHERE Booked <= CONVERT(int, DATEADD(year, DYYYY-YEAR(GETDATE()), DATEADD(day, DATEDIFF(day, 2, GETDATE()), 0)))
      GROUP BY DYYYY, DIVISION
      ORDER BY DIVISION, DYYYY
    OPTION (MAXRECURSION 0);

答案 1 :(得分:3)

好写不使用递归CTE :) 由于您已将年份存储在B101BookingsDetails表中,因此只需获取大于您所寻找年份的年份列表。

CREATE PROCEDURE dbo.testt1
(
    @YearToGet int = 2005
)
AS

    WITH Years AS (
        SELECT DISTINCT DYYYY as year
        FROM    dbo.B101BookingsDetails
        WHERE DYYYY >= @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 
                INNER JOIN Years
                    ON B101BookingsDetails.DYYYY = Years.Year
        WHERE   Booked  <= CONVERT(int,DateAdd(year, Years.Year - Year(getdate()), DateAdd(day, DateDiff(day, 2, getdate()), 0)))
        GROUP BY DYYYY, DIVISION

答案 2 :(得分:0)

你需要在循环结束时增加@YearToGet。