在自引用表上编写递归SQL查询

Mik*_*ran 4 sql sql-server recursion common-table-expression

我有一个数据库,其中包含一个名为Items的表,其中包含以下列:

  • ID - 主键,uniqueidentifier
  • 名称 - nvarchar(256)
  • ParentID - uniqueidentifier

name字段可用于构建项目的路径,方法是遍历每个ParentId,直到它等于'11111111-1111-1111-1111-111111111111',这是一个根项.

所以如果你有一个像行一样的表

ID                                   Name        ParentID
-------------------------------------------------------------------------------------
11111111-1111-1111-1111-111111111112 grandparent 11111111-1111-1111-1111-111111111111
22222222-2222-2222-2222-222222222222 parent      11111111-1111-1111-1111-111111111112
33333333-3333-3333-3333-333333333333 widget      22222222-2222-2222-2222-222222222222
Run Code Online (Sandbox Code Playgroud)

所以如果我在上面的例子中查找了一个id为'33333333-3333-3333-3333-333333333333'的项目,我想要的是路径

/grandparent/parent/widget 
Run Code Online (Sandbox Code Playgroud)

回.我试图写一个CTE,因为它看起来就像你通常会完成这样的事情 - 但由于我不做很多SQL,我无法弄清楚我哪里出错了.我已经看了一些例子,这和我似乎能够得到的一样 - 只返回子行.

declare @id uniqueidentifier
set @id = '10071886-A354-4BE6-B55C-E5DBCF633FE6'
;with ItemPath as (
    select a.[Id], a.[Name], a.ParentID 
        from Items a
            where Id = @id

    union all

    select parent.[Id], parent.[Name], parent.ParentID 
        from Items parent 
            inner join ItemPath as a
                on a.Id = parent.id
                    where parent.ParentId = a.[Id]
)
select * from ItemPath
Run Code Online (Sandbox Code Playgroud)

我不知道我如何为路径声明一个局部变量,并在递归查询中继续追加它.在尝试之前,我打算尝试至少将所有行都输送到父级.如果有人也可以提供帮助 - 我会很感激.

Rom*_*kar 10

以及这里的工作解决方案

SQL FIDDLE示例

declare @id uniqueidentifier
set @id = '33333333-3333-3333-3333-333333333333'

;with ItemPath as 
(
    select a.[Id], a.[Name], a.ParentID 
    from Items a
    where Id = @id

    union all

    select parent.[Id], parent.[Name] + '/' + a.[Name], parent.ParentID 
    from ItemPath as a
        inner join Items as parent on parent.id = a.parentID
)
select * 
from ItemPath
where ID = '11111111-1111-1111-1111-111111111112'
Run Code Online (Sandbox Code Playgroud)

我不喜欢它,我认为更好的解决方案是以其他方式做到这一点.等一下,我尝试写另一个查询:)

在这里更新

SQL FIDDLE示例

create view vw_Names
as
    with ItemPath as 
    (
        select a.[Id], cast(a.[Name] as nvarchar(max)) as Name, a.ParentID 
        from Items a
        where Id = '11111111-1111-1111-1111-111111111112'

        union all

        select a.[Id], parent.[Name] + '/' + a.[Name], a.ParentID 
        from Items as a
            inner join ItemPath as parent on parent.id = a.parentID
    )
select * 
from ItemPath
Run Code Online (Sandbox Code Playgroud)

现在你可以使用这个视图了

declare @id uniqueidentifier
set @id = '33333333-3333-3333-3333-333333333333'

select * 
from vw_Names where Id = @id
Run Code Online (Sandbox Code Playgroud)