There are a couple of ways to approach this. One way would be to use a db_map call for the original "set sql" statement and one db_map call for each of the dynamic parts like extra_orderby and extra_where. Then just let the query string built up and passed to the template::query as it originally was. Doing it this way, you wouldn't need to have anything for the template::query in the .xql file.