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?