单表上的递归查询

时间:2013-12-22 03:20:32

标签: sql sql-server

我有一个遵循以下结构的表格;

Tablename: Codes
ID int
CodeID int
ParentID int
Name varchar

是否可能在MSSQL 2012中在CTE中执行查询以递归方式选择所有值?

如果CodeID = NULL,那么这是代码的根。当你走下一步时,ParentID将与CodeID相关。

例如SELECT Name FROM Codes其中ID = null AND ParentID = X

先谢谢。

1 个答案:

答案 0 :(得分:1)

递归选择所有值是什么意思?以下选择所有值:

select *
from codes;

让我假设你想要层次结构中所有代码的所有祖先。您可以使用递归CTE执行此操作:

with cte as (
      select c.id, c.codeid, c.parentid, c.name,
             cast(c.id as varchar(255)) as ids
      from Codes c
      union all
      select cte.id, cte.codeid, c.parentid, cte.name,
             cast(cte.ids +','+cast(c.parentid as varchar(255)) as varchar(255))
      from cte join
           Codes c
           on cte.parentid = c.id and c.parentid is not null and
              ','+cast(cte.parentid as varchar(255))+',' not like '%,'+ids+'%,'
    )
select *
from cte;

您可以对特定的父ID进行过滤,以获取其下的所有节点。

Here是一个显示工作版本的SQL小提琴。

相关问题