Chinaunix首页 | 论坛 | 博客
  • 博客访问: 457385
  • 博文数量: 141
  • 博客积分: 211
  • 博客等级: 入伍新兵
  • 技术积分: 1049
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-17 16:25
个人简介

如此经年,望尽千帆。

文章分类

全部博文(141)

文章存档

2014年(73)

2013年(65)

2012年(3)

我的朋友

分类: SQLServer

2013-03-04 19:23:34

sql递归查询的例子,图文并茂,通俗易懂,有需要的朋友参考下了。

首先,创建数据表ptable 


点击(此处)折叠或打开

  1. CREATE TABLE [ptable](
  2.  [id] [int] NULL,
  3.  [pid] [int] NULL,
  4.  [name] [nchar](10)
  5. )
  6. GO
  7. INSERT INTO ptable VALUES(1,0,'a')
  8. INSERT INTO ptable VALUES(2,0,'b')
  9. INSERT INTO ptable VALUES(3,1,'c')
  10. INSERT INTO ptable VALUES(4,1,'d')
  11. INSERT INTO ptable VALUES(5,2,'e')
  12. INSERT INTO ptable VALUES(6,3,'f')
  13. INSERT INTO ptable VALUES(7,3,'g')
  14. INSERT INTO ptable VALUES(8,4,'h')
  15. GO
如下图:

下面开始sql递归查询的例子。

1、查询出1结点的所有子结点 


点击(此处)折叠或打开

  1. --查询出1结点的所有子结点
  2. with tmp as(select * from ptable where id = 1
  3.  union all select ptable.* from tmp, ptable where tmp.id = ptable.pid
  4. )
  5. select * from tmp
如下图:

2、查询出8结点的所有父结点


点击(此处)折叠或打开

  1. --查询出8结点的所有父结点
  2. with tmp as(select * from ptable where id = 8
  3.  union all select ptable.* from tmp, ptable where tmp.pid = ptable.id
  4. )
  5. select * from tmp;
如下图:


3、递归删除1结点和所有子结点 


点击(此处)折叠或打开

  1. --递归删除1结点和所有子结点
  2. with tmp as(select * from ptable where id = 1
  3.    union all select ptable.* from tmp, ptable where tmp.id = ptable.pid
  4. )
  5. delete from ptable where exists (select id from tmp where tmp.id = ptable.id)
如下图:


以上内容参考了部分网友的文章,在此感谢原作者。
原创文章,转载请注明原始链接:

阅读(1981) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~