IC_
IC_

Reputation: 1789

Create a concatenated table from another table using function

I have a function GetChildren(@id uniqueidentifier) that returns a table of nodes and a table of parents deleted from delete trigger I want to make a big table of nodes concatenating output of GetChildren for each row.Id of deleted, how do I do that? Please, say how to make it without variables and loops in only pure sql-way

I want something similar to SelectMany from linq c#

example:

deleted table

+-----+
| Id  |
+-----+
| 111 |
+-----+
| 222 |
+-----+

Nodes table

+-----+----------+
| Id  | ParentId |
+-----+----------+
| 111 | ...      |
+-----+----------+
| 222 | ...      |
+-----+----------+
| 333 | ...      |
+-----+----------+
| 444 | 111      |
+-----+----------+
| 555 | null     |
+-----+----------+
| 666 | 222      |
+-----+----------+

GetChildren('111') will produce:

+-----+
| Id  |
+-----+
| 111 |
+-----+
| 444 |
+-----+

GetChildren('222') will produce:

+-----+
| Id  |
+-----+
| 222 |
+-----+
| 666 |
+-----+

I want to get table that is concatenation of 2 above:

+-----+
| Id  |
+-----+
| 111 |
+-----+
| 444 |
+-----+
| 222 |
+-----+
| 666 |
+-----+

If deleted would contain 4 rows I want to concatenate all 4 outputs of GetChildren for each row

Upvotes: 0

Views: 101

Answers (1)

Brenton
Brenton

Reputation: 444

You can use CROSS APPLY to return and union multiple resultsets from a table valued function based on rows from another table. In your example that would look like:

SELECT c.*
FROM deleted d
CROSS APPLY GetChildren(d.Id) c

Upvotes: 3

Related Questions