码迷,mamicode.com
首页 > 数据库 > 详细

SqlServer with递归查询的使用

时间:2014-07-19 09:10:28      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   strong   数据   

1、数据准备
假定有一个表DiGui,有两个字段Id int ParentId int
Id ParentId
4 0
5 0
7 0
2 1
8 5
15 5
9 7
14 11
30 15
23 15
41 18
104 23
42 30
39 30
53 39
67 39
88 39
107 39

2、目的:通过传入ParentId(=5),返回该记录的所有递归数据,即
Id ParentId
8 5
15 5
30 15
23 15
42 30
39 30
53 39
67 39
88 39
107 39

3、Sql语句实现

with temp ( [Id], [parentid])
as
(
select Id, parentid
from DiGui
where [parentid] = 15
union all
select a.Id, a.parentid
from DiGui a
inner join temp on a.[parentid] = temp.[Id]
)
select * from temp

SqlServer with递归查询的使用,布布扣,bubuko.com

SqlServer with递归查询的使用

标签:style   blog   color   使用   strong   数据   

原文地址:http://www.cnblogs.com/gossip/p/3851021.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!