function sequence errors are quite generic; in my experience it means there is something wrong with the syntax of one of your statements.
Try to identify the statement, visually check for errors or break this down until it compiles, then check for errors inside the previous version.
Thank you for your reply. You are right the error message is very generic. The solutions to solve this problem from this site are all different, but it is good to try it all. Well, in our case we found the problem that caused this error. It was the time out issue. The query was running too long (longer than the default time allowed). We ran the same query for a much smaller table, then it works!