SQL语句递归写法~

Posted on 2011-06-28 00:35 黄超 阅读(838) 评论(0)  编辑 收藏 引用
Declare @Id Int 
Set @Id = 5; ---在此修改父节点 

With RootNodeCTE(Id,ParentId) 
As 

Select Id,ParentId From BOM Where ParentId In (@Id) 
Union All 
Select BOM.Id,BOM.ParentId From RootNodeCTE 
Inner Join BOM
On RootNodeCTE.Id = BOM.ParentId 


Select * From RootNodeCTE

需求在SQL Server 2000环境下的实现:

SQL code
create table AAA(ID INT,strNum1 varchar(8),strNum2 varchar(8),intTaxis int) insert into AAA select 1,'01' ,'001',1 insert into AAA select 2,'001','011',2 insert into AAA select 3,'001','010',1 insert into AAA select 6,'01' ,'002',2 insert into AAA select 4,'002','021',1 insert into AAA select 5,'002','022',2 go --创建用户定义函数 create function f_getChild(@strNum1 VARCHAR(10)) returns @t table(strNum1 VARCHAR(10),strNum2 VARCHAR(10),Level INT,Ord varchar(100)) as begin declare @i int set @i=1 insert into @t select strNum1,strNum2,@i,right('0'+strNum2,3) from AAA where strNum1 = @strNum1 while @@rowcount<>0 begin set @i=@i+1 insert into @t select a.strNum1,a.strNum2,@i,b.Ord+a.strNum2 from AAA a,@t b where a.strNum1=b.strNum2 and b.Level=@i-1 and not exists(select 1 from @t where strNum1=a.strNum1 and strNum2=a.strNum2) end return end go --执行查询 select * from dbo.f_getChild('01') order by Ord go --输出结果 /* strNum1 strNum2 Level Ord ---------- ---------- ----------- ----------- 01 001 1 001 001 010 2 001010 001 011 2 001011 01 002 1 002 002 021 2 002021 002 022 2 002022 */ --删除测试数据 drop function f_getChild drop table AAA go

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


posts - 12, comments - 0, trackbacks - 0, articles - 1

Copyright © 黄超