Fixing bugs in sql script