I have to update the flag as per below link . My logic is exactly like below mentioned logic (in the link) with 2 more nested loops inside the while loop.

[How To check minimum Date in each observation and update flag dynamically](https://stackoverflow.com/questions/45698391/how-to-check-minimum-date-in-each-observation-and-update-flag-dynamically/45702243?noredirect=1#comment78433083_45702243)

However, logic works fine and works smoothly for few rows. I have around 150000 rows (it will be more in future) and this looping is never ending. I checked the display plan and it says sort cost is 322112% and table Scan Cost is 242938%. Each row is looped.
Is there anyway we can make this code run faster ?