简体   繁体   中英

T-SQL Recursive Function - CTE with ParentID

I am trying to write a query in SQL Server to extract all of the information linked to a Task but I've hit a bit of a problem. What I want to happen is when I pass in a parameter (@TaskID) and for that to return task information for that ID and also any sub-task information related to that ID.

The problem is that once you reach the first sub-task it effectively loses its link to the overall Parent TaskID. For example: TaskID (3) is ultimately linked to TaskID (1) but because it's a sub-task of TaskID (2) there is no way to check unless I join the Parent (TaskID 1) to TaskID 2 and then to TaskID 3.

What we would like to do is have an infinite number of sub-tasks but that would require too many joins.

I was wondering if there was a better way?

Table structure or query wise.

Sample Table Structure 表结构

WITH cte AS (
SELECT
    t.TaskID
    ,t.Title
    ,t.ParentID
    ,CAST(t.TaskID AS NVARCHAR(MAX)) [Path]
FROM 
    tasks.Tasks t
WHERE 
    t.TaskID = 3

UNION ALL

SELECT
    c.ParentID  
    ,c.Title
    ,t.ParentID
    ,c.[Path] + '->' + CAST(t.TaskID AS NVARCHAR(MAX))
FROM
    tasks.Tasks t
    INNER JOIN cte c on c.ParentID = t.TaskID
)

SELECT 
    cte.TaskID
    ,cte.Title
    ,cte.[Path]
FROM 
    cte
WHERE 
    cte.ParentID IS NULL

This gives the correct result but I should really pass the TaskID without the ParentID as this would be the top level. So instead of t.TaskID = 3 in my code block, I would want to pass 1. I'll have a play...

This worked for me. Passing '1' as the TaskID will now allow me to see all the sub-tasks related to it (in the example 2 & 3).

WITH cte AS 
(
SELECT 
    t.TaskID
    ,t.Title
    ,t.ParentID 
    ,CONVERT(VARCHAR(MAX),'') AS [Path]
FROM 
    tasks.Tasks t
WHERE 
    t.ParentID IS NULL
    AND t.TaskID = @TaskID

UNION ALL

SELECT 
    sub.TaskID 
    ,sub.Title 
    ,sub.ParentID 
    ,cte.[Path] + '->' + CONVERT(VARCHAR(MAX),sub.TaskID) AS [Path]
FROM 
    tasks.Tasks sub
    INNER JOIN cte ON cte.TaskID = sub.ParentID
)

SELECT 
    cte.TaskID
    ,cte.Title
    ,cte.ParentID
    ,CONVERT(VARCHAR(MAX),@TaskID) + cte.[Path] AS [Path]
FROM 
    cte

Thanks for the help everyone

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