Fixed some bugs for generated sql