Home  >  Article  >  Database  >  mssql server 递归查询的sql语句

mssql server 递归查询的sql语句

WBOY
WBOYOriginal
2016-06-07 17:48:181226browse

下面介绍一下关于mssql server中使用递归的sql查询语哦,有需要的朋友可以参考一下。

张表(ColumnTable)的结构如下图所示

当前需要实现的功能:通过Number的值为67来获取当前的节点ID、父节点ID

递归实现SQL语句:


 代码如下 复制代码
with znieyu as<br>(<br> c.Id,c.FatherId,0 as lv1 from ColumnTable c where c.Number=67<br>union all<br>select c.Id,c.FatherId,lv1-1 from znieyu z<br>inner join ColumnTable c <br>on z.FatherId=c.Id<br>)<br>select znieyu.Id ,znieyu.FatherId,znieyu.lv1 as lv from znieyu
实现的效果:

满足条件67ID为6的递归-->6-->2(LV0)-->1(LV-1)-->0(LV-2)

满足条件67ID为8的递归-->8-->5(LV0)-->2(LV-1)-->1(LV-2)-->0(LV-3)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn