your description is too long to read my friend, so i don't know if this is what you need, ,but sql has an option called cross apply, which means that you perform a select statement and for each row returned, sql will invoke a function (this function may return a table by itself)