Got the main loop to use a cursor, rather than querying for one record at a time