DECLARE @Counter_temp INT-- I'm not convinced that this line is required SET @Counter_temp = 1-- I'm not convinced that this line is required While @Counter_temp <= (SELECT MAX(Key_m) FROM Time_definition_SPLIT) begin -- I'm not convinced that this line is required SELECT Time_ref, Time_instance, Geo_class, Aggregated_area, Super_classed_disease_cat, Cause, Constraint_ref, Sex, Sex_code, Age_start, Age_end, Age_range, Sum_count = SUM(G.Converted_person_count) INTO #tmp_G_P_M_CC FROM Geo_postaggregated_mortality_count_with_cause_catagory_SPLIT G, Time_definition_SPLIT T WHERE T.Key_m = @Counter_temp AND G.Time_instance = T.Instance_tag GROUP BY G.Time_ref, G.Time_instance, G.Geo_class, G.Aggregated_area, G.Super_classed_disease_cat, G.Cause, G.Constraint_ref, G.Sex, G.Sex_code, G.Age_start, G.Age_end, G.Age_range SET @Counter_temp = @Counter_temp + 1 end