Home > Database > Mysql Tutorial > MSSQL中递归SQL查询语句实例说明-

MSSQL中递归SQL查询语句实例说明-

WBOY
Release: 2016-06-07 18:02:49
Original
989 people have browsed it

MSSQL中递归SQL查询语句分享,需要的朋友可以参考下。

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

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

递归实现SQL语句:
代码如下:
with znieyu as
(
select c.Id,c.FatherId,0 as lv1 from ColumnTable c where c.Number=67
union all
select c.Id,c.FatherId,lv1-1 from znieyu z
inner join ColumnTable c
on z.FatherId=c.Id
)
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)
很简单的一个SQL递归,记录下来...

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template