move sql query into cycle