Fixed a lot of sql problems