Fixed SQL generation causing UndefineTable error