• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
一天到晚游泳的鱼
博客园    首页    新随笔    联系   管理    订阅  订阅

SQL 递归查询

CREATE TABLE [ptable](
 [id] [int] NULL,
 [pid] [int] NULL,
 [name] [nchar](10)
)
GO
INSERT INTO ptable VALUES(1,0,'a')
INSERT INTO ptable VALUES(2,0,'b')
INSERT INTO ptable VALUES(3,1,'c')
INSERT INTO ptable VALUES(4,1,'d')
INSERT INTO ptable VALUES(5,2,'e')
INSERT INTO ptable VALUES(6,3,'f')
INSERT INTO ptable VALUES(7,3,'g')
INSERT INTO ptable VALUES(8,4,'h')
GO

--查询出1结点的所有子结点
with tmp as(select * from ptable where id = 1
 union all select ptable.* from tmp, ptable where tmp.id = ptable.pid
)
select * from tmp 

--查询出8结点的所有父结点
with tmp as(select * from ptable where id = 8
 union all select ptable.* from tmp, ptable where tmp.pid = ptable.id
)
select * from tmp;

--递归删除1结点和所有子结点的语句:
with tmp as(select * from ptable where id = 1
   union all select ptable.* from tmp, ptable where tmp.id = ptable.pid
)
delete from ptable where exists (select id from tmp where tmp.id = ptable.id) 
posted @ 2012-03-31 16:05  Pato'  阅读(346)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3