简体   繁体   中英

How to know if a child exists on any nest level in a tree structure

I have a tree table, as showing:

TREE (TreeID int PK, ParentID int)

What I'm trying to figure is if I select a Tree item, how to know if the child exists in any sub level of its parent, and if it was a function, I would assume it would look something like this?

@ParentID --@param, The TreeID of the Tree item in focus

SELECT TreeID 
FROM TREE 
WHERE dbo.IsATreeChild(TreeID,@ParentID) = 1

Basically, If TreeId IsATreeChild of @ParentID it should return true. I just can't understand how to do this either way.

Any suggestions?

Recursive CTEs are quite common helpers for trees handling.

Probably you may find useful following functions:

create function dbo.ftTreeNodeChildren(@treeID int)
RETURNS TABLE
AS RETURN
    with Children(TreeID) as (
        select TreeID
        from Tree
        where ParentID = @treeID
        union all
        select T.TreeID
        from Children C
            join Tree T on T.ParentID = C.TreeID
    )
    select TreeID
    from Children
GO

It can be used then as:

select TreeID
from dbo.ftTreeNodeChildren(@treeID)

which should list children of @treeID (if there are any).

Sometimes it can be useful to include @treeID itself. In this case similar function can be used:

create function dbo.ftTreeNodeSubtree(@treeID int)
RETURNS TABLE
AS RETURN
    with Subtree(TreeID) as (
        select TreeID
        from Tree
        where TreeID = @treeID
        union all
        select T.TreeID
        from Subtree S
            join Tree T on T.ParentID = S.TreeID
    )
    select TreeID
    from Subtree
GO

which should list children or @treeID (if there are any) including @treeID itself.

upd.: To check that @treeID is a child of @parentID at any level you can use first function as:

if exists (
    select 1
    from dbo.ftTreeNodeChildren(@parentID)
    where TreeID = @treeID
)
    print '@treeID is a child of @parentID'
else
    print '@treeID is NOT a child of @parentID'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM