返回自引用MSSQL表

时间:2017-07-14 05:36:33

标签: sql-server common-table-expression

我想从子记录中获取父链。 父级或整个层次结构的所有子级。

在这里查看:https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql 在点“ F。使用递归公用表表达式来显示分层列表”这对于我想要做的事情是关闭的,但只需要单个子行的parentage(ID列表)。 / p>

这是我的数据:

CREATE TABLE dbo.Stuff  
    (StuffID int PRIMARY KEY NOT NULL,  
    ParentID int NULL,
    [Name] varchar(25) NOT NULL, 
    [Desc] text NULL)  
GO 

insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (1, null, 'My Home', '1203 WoodHaven Rd')
insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (2, 1, 'Basement', 'Walkout basement')
insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (3, 1, 'Level 1', 'Family room')
insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (4, 1, 'Level 2', 'Living/Kitchen')
insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (5, 1, 'Level 3', 'Bedrooms & Laundry')
insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (6, 1, 'Attic', 'attic space')
insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (7, 2, 'Family Room', 'Family game room')
insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (8, 2, 'Storeroom', 'Storage room')
insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (9, 2, 'Furnace', 'Furnace/Server room')
insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (10, 7, 'Closet', 'Under stairs junk closet')
insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (11, 9, 'Furnace floor', 'Furnace Room Floor (under desk)')
insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (12, 9, 'Furnace keyboard Shelf', 'Furnace room name desk shelf')
insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (13, 9, 'Furnace High Shelf', 'Furnace/Server room high shelf')
insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (14, 13, 'Router', 'ASUS AC router')
insert dbo.stuff (StuffID, ParentID, [Name], [Desc])
    VALUES (15, 13, 'Deprecated server', 'Old WinServer')

我想知道'路由器'在哪里。我期望的结果是:     1     2     9     13     14 我可能会用部分名称搜索它:     WHERE [名称] LIKE'%rout%'

1 个答案:

答案 0 :(得分:0)

;with parents as
(
    select 
        StuffID, ParentID
    from 
        [Stuff]
    WHERE 
        [Name] LIKE '%rout%'
    union all
    select
        s.StuffID, s.ParentID
    from
        [Stuff] s
    join parents p on
        s.StuffID = p.ParentID
)
SELECT 
    StuffID 
from 
    parents
order by 
    StuffID

输出将是:1 2 7 13 14(与您的预期不同1 2 9 13 14,这是一个错误吗?)