1

T-SQL Tree Search

Select from set of nodes if they are under a parent

I have a very large tree in a MSSQL Db (80000+) records. My client has requested a quick search of the tree via a text LIKE command. The LIKE command returns < 500 records.

Is there some recursive command that will check the tree of each quickly to see if they are under a particular node?

Edit: I thought it was fairly clear however....

I am on SQL Server 2005.

Table Schema
 - (pK) Id
 - (fK) ParentId
 - FirstName
 - LastName

I have recursive calls that are able to go down several levels quickly. however to do the Name search I would have to poll the entire tree which can be several hundred levels deep and is not an option. I was hoping for help designing a query so I can search the entire table first for the name match and filter the records that are not part of the tree in question.

4

2 回答 2

2

您可以使用递归 CTE 来做到这一点——您需要代码示例吗?

像这样(这段代码已经过测试)

WITH recurseTree AS
(
   SELECT * 
   FROM tableName
   WHERE Id = @parentID
   UNION ALL
   SELECT c.*
   FROM tableName c
   JOIN recurseTree p ON c.parentID = p.id
)
SELECT * 
FROM recurseTree

注意:更多新版本(2008+)为您提供了一种特殊的数据类型(hierarchyid),用于进行快速树遍历。这可能是最好的方法,其他任何事情都不会那么快。升级!!

于 2012-08-01T15:22:12.223 回答
1

这应该可以帮助您:

;WITH CTE AS
(
    SELECT Id, ParentId, FirstName, LastName
    FROM YourTable
    UNION ALL
    SELECT B.Id, B.ParentId, B.FirstName, B.LastName
    FROM CTE A 
    INNER JOIN YourTable B
    ON A.ParentId = B.Id
)
SELECT *
FROM CTE
WHERE FirstName LIKE '%something%'
OPTION(MAXRECURSION 0)
于 2012-08-01T15:38:15.930 回答