Personally, I would probably move this to a script and build the query dynamically, and then call it with system.db.runPrepQuery(). Named Queries are great and should be the default solution, IMO, however, they aren't the correct solution for every situation. Let the scripting handle the logic for you, it's really good at that, and then the DB can do what it does best.