use EnVisage go declare @cutStartDate datetime set @cutStartDate = '2021-01-01' declare @newMaxDate datetime declare @oldMaxDate datetime --STEP 1. Check if there is data that prevents from cutting the calendar if exists(select id from Scenario where EndDate >= @cutStartDate and Type in (1,2,3)) raiserror('There are records in Scenario (with type of 1, 2 or 3) with EndDate greater than given cut start date - script cannot run until these records are in the database', 16, 1) if exists(select ScenarioDetail.id from ScenarioDetail inner join Scenario on Scenario.Id = ScenarioDetail.ParentID where WeekEndingDate >= @cutStartDate and Scenario.Type in (1,2,3)) raiserror('There are records in ScenarioDetail (with scenario with type of 1, 2 or 3) with WeekEndingDate greater than given cut start date - script cannot run until these records are in the database', 16, 1) if exists(select id from TeamAllocation where WeekEndingDate >= @cutStartDate) raiserror('There are records in TeamAllocation with WeekEndingDate greater than given cut start date - script cannot run until these records are in the database', 16, 1) if exists(select id from PeopleResourceAllocation where WeekEndingDate >= @cutStartDate) raiserror('There are records in PeopleResourceAllocation with WeekEndingDate greater than given cut start date - script cannot run until these records are in the database', 16, 1) if exists(select id from PeopleResourceTraining where WeekEndingDate >= @cutStartDate) raiserror('There are records in PeopleResourceTraining with PeopleResourceTraining greater than given cut start date - script cannot run until these records are in the database', 16, 1) if exists(select id from PeopleResourceVacation where WeekEndingDate >= @cutStartDate) raiserror('There are records in PeopleResourceVacation with PeopleResourceVacation greater than given cut start date - script cannot run until these records are in the database', 16, 1) --STEP 2. Store old calendar MaxDate and delete FC records starting with given date select @oldMaxDate = max(EndDate) from FiscalCalendar where Type = 0 print ('old max date ' + cast(@oldmaxdate as nvarchar)) delete from FiscalCalendar where StartDate >= @cutStartDate --STEP 3. Select new calendar Max date select @newMaxDate = max(EndDate) from FiscalCalendar where Type = 0 print ('new max date ' + cast(@newMaxDate as nvarchar)) --STEP 4. Update People resource - set permanent (new max date) to those who was permanent on old FC (old max date) update PeopleResource set EndDate = @newMaxDate where EndDate = @oldMaxDate --STEP 5. Cut Actual and Planned capacities delete from ScenarioDetail where ScenarioDetail.WeekEndingDate > @newMaxDate and ScenarioDetail.ParentID in (select id from scenario where type in (13,14)) update Scenario set EndDate = @newMaxDate where EndDate = @oldMaxDate and type in (13,14)