SET NOCOUNT ON;

DECLARE @ID uniqueidentifier, @BUDirectCosts decimal(15,4), 
	@Cost decimal(15, 4), @Year int, @Month int;

DECLARE scenario_cursor CURSOR FOR 
SELECT ID, BUDirectCosts
FROM Scenario s WHERE not s.CostSavings is null;

OPEN scenario_cursor

FETCH NEXT FROM scenario_cursor INTO @ID, @BUDirectCosts

WHILE @@FETCH_STATUS = 0
BEGIN
   
    DECLARE cost_saving_cursor CURSOR FOR 
    SELECT [Year], cost, [Month] 
    FROM CostSaving 
    WHERE ScenarioId = @ID and not cost is null	order by [Year], [Month]

	declare @CostSavingsSum decimal(15,4)
	set @CostSavingsSum = 0
	update Scenario set ROIDate =null where id = @ID

    OPEN cost_saving_cursor
    FETCH NEXT FROM cost_saving_cursor INTO @Year, @Cost, @Month

    WHILE @@FETCH_STATUS = 0
    BEGIN
		set @CostSavingsSum = @CostSavingsSum + @Cost 
		
		if (@CostSavingsSum >= @BUDirectCosts)
		BEGIN
			print cast(@CostSavingsSum as nvarchar(20)) +'|'+ cast(@BUDirectCosts as nvarchar(20))
			print cast(CAST(CONVERT(VARCHAR, @Year) + '-' + CONVERT(VARCHAR, @Month) + '-1' AS DATETIME) as varchar(10))
			update Scenario set ROIDate =  CAST(CONVERT(VARCHAR, @Year) + '-' + CONVERT(VARCHAR, @Month) + '-1' AS DATETIME)
			where id = @ID
			BREAK
        END 
        FETCH NEXT FROM cost_saving_cursor INTO @Year, @Cost, @Month
    END
			
    CLOSE cost_saving_cursor
    DEALLOCATE cost_saving_cursor
    
    FETCH NEXT FROM scenario_cursor INTO @ID, @BUDirectCosts
END 
CLOSE scenario_cursor;
DEALLOCATE scenario_cursor;