从递归表中获取值

时间:2017-02-17 18:09:07

标签: sql sql-server

我有一张桌子:

ParentNode | Node      | Children
---------- | --------- | ---------
NULL       | Parent_1  | true
Parent_1   | Child_1   | true
Child_1    | Child_2   | true
Child_2    | Value1    | false
NULL       | Parent_2  | true
Parent_2   | Child_1   | true
Child_1    | Value2    | false

我需要一个返回值路径的函数:

select Node, MyFunction(Node) as Path from myTable where Children = 'false'

预期结果是:

Node   | Path
------ | ---------
Value1 | Parent_1/Child_1/Child_2
Value2 | Parent_2/Child_1

任何想法?

3 个答案:

答案 0 :(得分:2)

尝试一下,我没有测试过它。

WITH tree AS
(
    SELECT c1.Node, c1.ParentNode, [level] = 1, path = cast(c1.Node as varchar(300))
    FROM dbo.[table] c1
    WHERE c1.ParentNode = 'value 1'
    UNION ALL
    SELECT c2.Node, c2.ParentNode, [level] = tree.[level] + 1, 
           Path = Cast(tree.path + '/' + c2.Node as varchar(300))
    FROM dbo.[table] c2 INNER JOIN tree ON tree.Node = c2.ParentNode
)
SELECT tree.Node, tree.path
FROM tree
Order by path
OPTION (MAXRECURSION 0)

答案 1 :(得分:1)

您可以先定义一个递归调用自身的函数:

CREATE FUNCTION [dbo].[getFullPath]
(
    @node_name nvarchar(50)
)
RETURNS nvarchar(max)
AS
BEGIN
    declare @parent_name as nvarchar(50)
    declare @full_path as nvarchar(max)

    select  
    @parent_name = parentnode,
    @node_name = node
    from tree (nolock)
    where node = @node_name

    set @full_path = @node_name

    if(isnull(@parent_name,'') <> '')
    begin
        set @full_path = dbo.getFullPath(@parent_name) + '\' + @full_path
    end

    return @full_path
END
GO

然后在查询中使用它:

select
node,
dbo.getFullPath(node)
from tree

答案 2 :(得分:0)

我用这段代码找到了问题的解决方案:

typeof url // => "string"