SQL Server递归查询
来源:这里教程网
时间:2026-03-02 10:29:07
作者:
pid int,
parentid int,
name varchar(60)
)
insert into test_with values(1, null, 'A')
insert into test_with values(2, null, 'B')
insert into test_with values(3, null, 'C')
insert into test_with values(4, 1, 'A1')
insert into test_with values(5, 1, 'A2')
insert into test_with values(6, 1, 'A3')
update test_with set name = 'A2' where pid = 5
update test_with set name = 'A3' where pid = 6
select * from test_with
insert into test_with values(7, 4, 'A11')
insert into test_with values(8, 5, 'A22')
insert into test_with values(9, 6, 'A33')
with t(pid, parentid, name, level) as (
select pid, parentid, name, 0 as level from test_with where parentid is null
and pid = 1
union all
select test_with.pid, test_with.parentid, test_with.name, level+1 from t , test_with
where t.pid = test_with.parentid and test_with.parentid is not null
and t.pid <> test_with.pid
)
select * from t where level <= 3 OPTION(MAXRECURSION 5000)
with t(pid, parentid, name,parentname, level) as (
select pid, parentid, name, cast(null as varchar(60)) as parentname,0 as level from test_with where parentid is null
union all
select test_with.pid, test_with.parentid, test_with.name , t.name as parentname, level+1 from t , test_with
where t.pid = test_with.parentid
)
select * from t where level <= 3 OPTION(MAXRECURSION 5000)
可以用来模拟start with..connect by
在test_with.pid上纠结了许久,不小心写成t.pid,结果造成无限的递归出错:
消息 530,级别 16,状态 1,第 1 行
语句被终止。完成执行语句前已用完最大递归 5000。
这个特性在Oracle 11g, 12c也已支持
编辑推荐:
- SQL Server递归查询03-02
- SQL Server动态SQL,绑定变量03-02
- 教你电子邮箱格式怎么写03-02
- Windows2008(X64)安装32位SQL2005的IIS功能要求警告解决方法03-02
- SQL Server游标使用练习03-02
- 2014 Kobe Basketball Shoes Nike Hyperposite Amare Stoudemire Knicks PE03-02
- The Rams have three firstround picks on the resistive line and the fourth03-02
- mssql常用基础函数03-02
下一篇:
相关推荐
-
雷神推出 MIX PRO II 迷你主机:基于 Ultra 200H,玻璃上盖 + ARGB 灯效
2 月 9 日消息,雷神 (THUNDEROBOT) 现已宣布推出基于英
-
制造商 Musnap 推出彩色墨水屏电纸书 Ocean C:支持手写笔、第三方安卓应用
2 月 10 日消息,制造商 Musnap 现已在海外推出一款 Oce
热文推荐
- 2016年10月显卡天梯图 桌面级显卡天梯图
2016年10月显卡天梯图 桌面级显卡天梯图
26-03-02 - 教你电子邮箱格式怎么写
教你电子邮箱格式怎么写
26-03-02 - Windows2008(X64)安装32位SQL2005的IIS功能要求警告解决方法
- mssql2000下批量附加/分离数据库(sql语句)
mssql2000下批量附加/分离数据库(sql语句)
26-03-02 - windowsserver2008R2安装sqlserver2000遇到的种种问
- bak文件打开教程
bak文件打开教程
26-03-02 - SQL Server 2008安装注意事项
SQL Server 2008安装注意事项
26-03-02 - 固态硬盘与普通硬盘的区别概述
固态硬盘与普通硬盘的区别概述
26-03-02 - 2016年10月CPU天梯图 桌面级CPU天梯图
2016年10月CPU天梯图 桌面级CPU天梯图
26-03-02 - 电脑显卡驱动怎么安装
电脑显卡驱动怎么安装
26-03-02
