by Nadirshah Ferozepurwalla.
For anyone who decides to help here, for the time being
I have altered the code where it forms the temp table to only include users which are already present in moodle db.
This exttemp table is further used as the AD source table to compare with internal moodle database. Hoping this would work.