Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Recursive SQL query to return all rows from table with parent-child relationship

$
0
0

I have a table named Entity (EntityId, ParentId, Name, Address, ect ). There is a parent-child relationship with EntityId-ParentId that can go many levels deep. I would like to create return all the descendant child rows for a entity.

Parent

Child 

Child 

Grandchild

This is the query I am currently trying:

CREATE PROCEDURE [dbo].[testChildren]
@Parent int
AS
BEGIN
SET NOCOUNT ON;
WITH EntityChildren AS
(
SELECT *  FROM Entity WHERE EntityId = @Parent
UNION ALL
SELECT * FROM Entity e INNER JOIN EntityChildren e2 on e.EntityParent = e2.EntityId
)
SELECT * from EntityChildren
END

When running it, I get the following error: "All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists."

Am I going about this the wrong way?


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>