SQL Server - 从特定元组开始的递归

时间:2014-09-04 17:12:58

标签: sql sql-server recursive-query

我来自这里[a link]的示例,它解释了如何编写递归查询。

WITH security_menu_Recursive(Parent,MenuId,MenuName,LEVEL)
AS
(
    SELECT vparent,vmenuid,vmenuname,0 AS LEVEL FROM dbo.SecurityMenu WHERE vParent = null
    UNION ALL
    SELECT vparent,vmenuid,vmenuname,Level + 1 AS LEVEL FROM dbo.SecurityMenu
    INNER JOIN security_menu_Recursive AS smr ON smr.menuid = dbo.SecurityMenu.vParent
)
SELECT parent,menuid,menuname,LEVEL FROM security_menu_Recursive

这对我来说很有用,但是我正在寻找从特定元组开始递归,在上面的示例中,例如从MenuId为102开始。

我尝试在三个SELECT中添加条件WHERE vmenuid = 102,但它没有用。

1 个答案:

答案 0 :(得分:1)

如果只是用vmenuid = 102条件替换锚的空检查,它应该可以正常工作;

WITH security_menu_Recursive(Parent,MenuId,MenuName,LEVEL)
AS
(
    SELECT vparent,vmenuid,vmenuname,0 AS LEVEL FROM dbo.SecurityMenu WHERE vMenuid=102
    UNION ALL
    SELECT vparent,vmenuid,vmenuname,Level + 1 AS LEVEL FROM dbo.SecurityMenu
    INNER JOIN security_menu_Recursive AS smr ON smr.menuid = dbo.SecurityMenu.vParent
)
SELECT parent,menuid,menuname,LEVEL FROM security_menu_Recursive