You can't do loops and stuff in pure SQL. It's a query language not a real programming language. That's why there's PL/SQL in Oracle, T-SQL in SQL Server, etc. Those are really extensions to SQL so that you -can- program around your queries and make nice decision trees.
The only thing remotely resembling programming are CASE statements which let you do a sort of if else constructions, but they can get ugly real fast.
So either do it in Java with JDBC like Jeanne suggested or if that's not possible
you should try something like PL/SQL.