Well first of all, if it does work sometimes then it is most likely an issue with another thread writing to the table before you pull and read from it in that thread. However you have given us little code to go off in order to debug the other possible thread that might be causing this irritant.
So instead ill recommend you something else. The debugger is really good for these scenarios. With it you can follow your script in real time and see all the changes to your values and so forth. I would place down a breakpoint somewhere in that area of code and just follow your script down its lines of logic. Look for anything that might seem to be peculiar, and when you find something get back to us and post your findings.