Move query statement creation inside while loop.

Change-Id: I4aad1798cf1fcff68dac5f9da269e6e27f8870e3