It would also help if you indented your code consistently. As it is, it's very hard to understand what happens when in what order.
However it looks like there's some code which tries to compare two dates. And it looks like one of the dates is formatted using this:
This is going to produce something like "9-Jan-2014" or "17-Feb-2014". If you do a
string comparison on those two you will find that "17-Feb-2014" comes before "9-Jan-2014". On the other hand the other date appears to be formatted by the database so there's no telling whether it looks like that or like "20140301".
You should use Date objects in this comparison, not String objects.
Also your database query looks like it might select a lot of database records, but your while-loop only saves data from the last record. Was that intentional, or do you just expect the query to return one record?