Fixing bugs in SQL script