单个参数SQL Server存储过程的同时结果

时间:2016-05-04 03:40:16

标签: sql sql-server tsql stored-procedures sql-server-2008-r2

我有以下t-sql:

declare @startdate datetime, @finishdate datetime;
declare @declinerate float, @setpoint float;
declare @recoveredmw;

set @startdate = '2016-01-01';
set @finishdate = '2016-12-31'
set @declinerate = 0.0972 / 100;
set @setpoint = 98;
set @recoveredmw = @setpoint - 1;

;WITH ctetest AS 
(
    SELECT      
        @StartDate AS CDate, 
        @setpoint as Case2, 
        0 as OLNo

    UNION ALL

    SELECT      
        dateadd(day,1,CDate),
        CASE 
           WHEN Case2 < @recoveredMW THEN @setpoint 
                                     ELSE (1 - @declinerate1) * Case2 
        END,
        OLNo + (CASE WHEN Case2 < @recoveredMW THEN 1 ELSE 0 END)
    FROM        
        ctetest 
    WHERE       
        dateadd(day, 1, CDate) <= @finishdate
)
SELECT * 
FROM ctetest OPTION (MAXRECURSION 0)

然后结果应该是:

---------------------------------
CDate          Case2       OLNo
---------------------------------
2016-01-01     98          0
2016-01-02     97.9        0
2016-01-03     97.81       0
ff.
2016-12-30     97.62       30
2016-12-31     97.52       30

它会根据@startdate@finishdate参数从1月1日到12月底创建数据。

我想要的是同时创建@recoveredMW。假设@setpoint为98,那么它将创建上面@recoveredMW的{​​{1}}从@setpoint减去1的结果。在2016-12-31之后,它会从头开始创建另一个原始数据,但@recoveredMW为负2,依此类推。

结果样本:

---------------------------------
CDate          Case2       OLNo
---------------------------------
2016-01-01     98          0
2016-01-02     97.9        0
2016-01-03     97.81       0
ff.
2016-12-30     97.62       30
2016-12-31     97.52       30
2016-01-01     97          0        <-- New RawData after 2016-12-31, @recoveredMW-2
2016-01-02     96.91       0
2016-01-03     96.81       0
ff.
2016-12-31     96.53       30

有办法做到这一点吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

在第一个锚点成员之后将另一个锚点成员添加到你的ctetest

        SELECT      @startdate AS CDate, 
                    @setpoint - 1 as Case2, 
                    0 as OLNo

如果您希望结果单独订购,请添加另一列以区分原始运行与@setpoint的{​​{1}}

这是修改后的查询

@setpoint - 1

编辑1:

;WITH ctetest AS 
        (
            SELECT      1 AS Data,   -- Added
            @startdate AS CDate, 
                        @setpoint as Case2, 
                        0 as OLNo

            UNION ALL

            SELECT      2 as Data,
            @startdate AS CDate, 
                        @setpoint - 1 as Case2, 
                        0 as OLNo

            UNION ALL

            SELECT      Data,
            dateadd(day,1,CDate),
                        CASE WHEN Case2 < @recoveredmw THEN @setpoint ELSE (1 - @declinerate) * Case2 END,
                        OLNo + (CASE WHEN Case2 < @recoveredmw THEN 1 ELSE 0 END)
            FROM        ctetest 
            WHERE       dateadd(day, 1, CDate) <= @finishdate
        )
        SELECT      * 
        FROM        ctetest 
    order by    Data, CDate
    OPTION (MAXRECURSION 0)