Kermit
Kermit

Reputation: 34062

Fetch result from function that returns table from query

I would like to fetch the result set from a function for each row of a parent result. Here is table1:

column
------
a1
a2
a3
a4
a5

I would like to loop through table1 and get the result of the function for each item in the column. The function returns a table.

SELECT (SELECT * FROM functionReturnsTable(a.column))
FROM (SELECT column FROM table1) a

I have tried the query above however I get the error

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

How can I write a query/function that will loop through table1 and combine the result of each item into a single table?

Upvotes: 1

Views: 179

Answers (1)

Aaron Bertrand
Aaron Bertrand

Reputation: 280615

Maybe something like this:

SELECT * FROM dbo.table1 AS a
CROSS APPLY dbo.functionReturnsTable(a.column) AS f;

Though you probably wouldn't use SELECT * in the production version, and you would probably always use schema prefix and statement terminators, right? :-)

Also, please stop thinking about this as a "loop"...

Upvotes: 3

Related Questions