I am trying to loop each time for a date for every member and define a status for a member. This query is working perfectly fine but this is taking lot of time. I cannot think of alternate way to get this result set.
Logic,
For every member, look for minimum date, then add 30 to it, if any date falls under 30, then status is initial_1. If it is greater than 30 and less than 30+15, then Reauth_1_1, if date greater than 30+16 , then it is intial_2.
MemberID DOS Status
HHH00031200 7/17/2014 Initial_1
HHH00031200 7/29/2014 Initial_1
HHH00031200 8/21/2014 Re-Auth_1_1
HHH00031200 8/27/2014 Re-Auth_1_1
HHH50000000 5/23/2016 Initial_1
HHH50000000 7/19/2016 Initial_2
HHH50000000 9/13/2016 Initial_3
HHH88844900 9/19/2015 Initial_1
HHH88844900 10/22/2015 Re-Auth_1_1
HHH88844900 11/24/2015 Re-Auth_1_2
HHH88844900 12/10/2015 Re-Auth_1_2
HHH22227700 1/16/2014 Initial_1
HHH22227700 2/21/2014 Re-Auth_1_1
HHH22227700 2/25/2014 Re-Auth_1_1
HHH22227700 3/5/2014 Re-Auth_1_1
HHH22227700 1/1/2015 Initial_2
HHH22227700 1/15/2015 Initial_2
HHH22227700 1/20/2015 Initial_2
HHH22227700 2/10/2015 Re-Auth_2_1
HHH22227700 2/12/2015 Re-Auth_2_1
HHH22227700 2/17/2015 Re-Auth_2_1
HHH22227700 2/19/2015 Re-Auth_2_1
HHH22227700 2/25/2015 Re-Auth_2_1
HHH22227700 2/26/2015 Re-Auth_2_1
Query:
--drop table #Temp_SO_Check
Select
*
Into #Temp_SO_Check
From #auth;
CREATE INDEX IDX_C_Users_UserID ON #Temp_SO_Check(MemberID,DOS,LoopLogic);
While Exists
(
Select Top 1
MemberID
From #Temp_SO_Check
Where LoopLogic Is Null
)
Begin
Select Top 1
@ID = MemberID
, @StartDate = DOS
From #Temp_SO_Check
Where LoopLogic Is Null
Order By
MemberID
, DOS;
If @PrevID <> @ID
Begin
set @Flag=1;
Set @LoopLogic ='Initial_'+Cast(@Flag as nvarchar(50)) ;
Set @PrevID = @ID;
set @ReauthFlag=0;
end
else
Begin
if((@LookupDate is not null) and (datediff(day,@LookupDate,@StartDate))<14)
Begin
Set @LoopLogic ='Re-Auth_'+Cast(@Flag as nvarchar(50)) ;
End
Else if ((@LookupDate is not null) and (datediff(day,@LookupDate,@StartDate))>14)
Begin
set @Flag=@Flag+1;
set @ReauthFlag=0;
Set @LoopLogic ='Initial_'+Cast(@Flag as nvarchar(50));
End
End
Set @LookupDate = DateAdd(Day, 30, @StartDate);
if( (@LoopLogic like '%Re-Auth_%') and (@LookupDate<>@LookupDate1))
Begin
Set @ReauthFlag=@ReauthFlag+1;
Set @LoopLogic ='Re-Auth_'+Cast(@Flag as nvarchar(50))+'_'+Cast(@ReauthFlag as nvarchar(50)) ;
End
set @LookupDate1=@LookupDate;
Update
#Temp_SO_Check
Set
LoopLogic = @LoopLogic
Where
MemberID = @ID
And DOS Between @StartDate
And @LookupDate;
End;
#auth table has my data and then the looping stats. i have 766000 records and it is taking more than 1 hour 30 minutes and still running.
Can anybody please help me fine tune this query?