下面介绍一下关于mssql server中使用递归的sql查询语哦,有需要的朋友可以参考一下。
张表(columntable)的结构如下图所示

当前需要实现的功能:通过Number的值为67来获取当前的节点ID、父节点ID
递归实现SQL语句:
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7">
<tr>
<td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td>
<td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onClick="doCopy('copy4736')">复制代码</td>
</tr>
<tr>
<td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy4736><pre class="brush:php;toolbar:false;">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)
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号