The system running slow or appearing to hang can be a number of things...

You are in a loop, not allowing other events to be processed.
SQL doesn't use database indexes (or none exist).
Lots of text comparisons in SQL Query