Sql递归查询来创建一个唯一的列表
问题描述:
为了速度的原因,我需要将一些代码从C#移动到一个存储过程。我想要得到的是基于CategoryId的RoleTemplates(或者CategoryToRoleTemplate)表格中的TemplateIds的唯一列表。
但是,我需要查询漫步Category.ParentId关系,并收集所有父级的相关TemplateIds。这需要发生,直到ParentId为空。Sql递归查询来创建一个唯一的列表
理想情况下,结果应该是RoleTemplate.TemplateIds的唯一列表。
表结构...
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)
我使用SQL Server 2008 R2。
谢谢!
编辑:
最终的解决方案:
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是关键。
答
我会建议CTE做这个查询。请记住,树实际上会从零开始,直到耗尽。
实例(可能会或可能无法正常工作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)
好点(Tm):不要忘记之前WITH关键字分号。
答
我现在时间很短,所以我不能具体说明,但是我会查看公用表表达式,过去我成功地用它来实现递归。