Some SQL fixes

I ran a debugger and found out what was wrong with a couple of functions.  I have included the fixed plus I cleaned up some of the SQL.