I think all the code you need exists around here:
- Execute a baq from a function
- Reference data in the results
- Insert records into a UD table
There are threads on all these topics just have to piece it together.
there are a couple to get you started . . .