代码之家  ›  专栏  ›  技术社区  ›  Kieron

创建唯一列表的Sql递归查询

  •  1
  • Kieron  · 技术社区  · 15 年前

    出于速度原因,我需要将一些代码从C#移到存储过程中。我试图从基于CategoryId的RoleTemplates(或CategoryToRoleTemplate)表中获得一个唯一的templateId列表。

    理想情况下,结果应该是RoleTemplate.templateId的唯一列表。

    Categories
    ------------------------------
    CategoryId    uniqueidentifier
    ParentId      uniqueidentifier <-- Relationship to Categories.CategoryId.
    Name          varchar (50)
    
    CategoryToRoleTemplate
    ------------------------------
    CategoryId    uniqueidentifier <-- Relationship to Categories.CategoryId.
    TemplateId    uniqueidentifier <-- Relationship to RoleTemplates.TemplateId.
    
    RoleTemplates
    ------------------------------
    TemplateId    uniqueidentifier
    Name          varchar (50)
    

    我使用的是SQLServer2008R2。

    编辑:

    最终解决方案:

    with CategoryHierarchy (ParentId)
    as (
        -- Anchor member definition
        select CategoryId from Categories
        where CategoryId = @id
        union all
    
        -- Recursive member definition
        (select c.ParentId from Categories as c
            inner join CategoryHierarchy as p
            on c.CategoryId = p.ParentId)
    )
    
    select distinct TemplateId from CategoryToRoleTemplates where CategoryId in (select CategoryId from CategoryHierarchy);
    

    感谢所有的回答!CTE是关键。

    4 回复  |  直到 15 年前
        1
  •  2
  •   Jubin Patel    11 年前

    我建议用CTE来做这个查询。但是请记住,树实际上将从null开始,直到耗尽为止。

    示例(根据您的代码,OOB可能工作,也可能不工作):

    ; WITH CategoryTree(CategoryID, sorthelp) AS
    (SELECT CategoryID, 0 FROM Categories WHERE ParentID IS NULL)
    
    UNION ALL
    
    (SELECT C.CategoryID, CT.sorthelp + 1 FROM Categories C INNER JOIN CategoryTree CT ON C.PARENTID = CT.CategoryID)
    
    SELECT DISTINCT TemplateID FROM RoleTemplates WHERE CategoryID IN (SELECT CategoryID FROM CategoryTree)
    

        2
  •  1
  •   Brentmeistergeneral    15 年前
        3
  •  1
  •   Bruno Costa    15 年前

    请检查此链接 http://msdn.microsoft.com/en-us/library/ms186243.aspx

    我将首先使用 具有 语法,然后与其他表联接。

        4
  •  1
  •   alex    15 年前