在工作中遇到一個問題,是需要sql
遞迴查詢的.不懂,於是到csdn上去問,那裡的效率真是非常高,我以前也沒在上面問過問題.問題描述:我有一個表結構如下:
id upperid
1 2
3 2
4 1
5 3具體層次不知道,我想用遞迴sql語句把所有屬於某個upperid的資料,包括它的子樹,都讀出去,請問應該子怎麼寫?
比如說 upperid =2
那麼先找到1,3,然後再由1,3找到4,5使用sql語句實現有兩位朋友都給了回複:
fa_ge(鶴嘯九天)Create table t(id int,upperid int)
insert into t
select 1, 2
union all select 3, 2
union all select 4, 1
union all select 5, 3
select * from t
create function aa(@upperid int)
returns @t table (id int,upperid int,level int)
as
begin
declare @i int
set @i=1
insert into @t
select *,@i from t where upperid=@upperid
while @@rowcount>0
begin
set @i=@i+1
insert into @t
select a.*,@i from t a left join @t b on a.upperid=b.id
where b.level=@i-1
end
return
endselect * from dbo.aa(1)id upperid level
----------- ----------- -----------
4 1 1(所影響的行數為 1 行)select * from dbo.aa(2)id upperid level
----------- ----------- -----------
1 2 1
3 2 1
4 1 2
5 3 2(所影響的行數為 4 行)
這個需要level這個數,否則得不到.
hellowork(一兩清風)----建立測試資料
if object_id('tbTest') is not null
drop table tbTest
if object_id('spGetChildren') is not null
drop proc spGetChildren
GO
create table tbTest(id int, upperid int)
insert tbTest
select 1, 2 union all
select 3, 2 union all
select 4, 1 union all
select 5, 3
GO
----建立預存程序
create proc spGetChildren @id int
as
declare @t table(id int)
insert @t select id from tbTest where upperid = @id
while @@rowcount > 0
insert @t select a.id from tbTest as a inner join @t as b
on a.upperid = b.id and a.id not in(select id from @t)
select * from @t
GO----執行預存程序
declare @upperid int
set @upperid = 2
EXEC spGetChildren @upperid----清除測試環境
drop proc spGetChildren
drop table tbTest/*結果
id
-----------
1
3
4
5
*/
這個就符合我的要求了.不過我需要的是一個函數,於是改寫如下;create function GetChildren (@id varchar(20))
returns @t table(id varchar(20))
as
begin
insert @t select wayid from tb where upperwayid = @id
while @@rowcount > 0
insert @t select a.wayid from tb as a inner join @t as b
on a.upperwayid = b.id and a.wayid not in(select id from @t)
return
end哈哈,真是爽啊.csdn問題地址:http://community.csdn.net/Expert/topic/5731/5731880.xml?temp=.8160211原來為瞭解決這個問題,本來想用遞迴的,在網上看到了下面的資料:
表結構是這樣的
部門 上層業務
A B
B C
C D
A A
B B
C C
求一條SQL語句,根據A查其上層業務,查詢結果為
上層業務
B
C
D
=================================================
用函數
create table tb (部門 varchar(20),上層業務 varchar(20))
insert into tb select 'A','B' union all select 'B','C' union all select 'C','D'
union all select 'A','A' union all select 'B','B' union all select 'C','C'
--select * from tb
create function test_f (@name varchar(20))
returns @ta table(上層業務 varchar(20))
as
begin
--select @name=上層業務 from tb where 部門=@name and 部門!=上層業務
while exists(select 1 from tb where 部門=@name and 部門!=上層業務)
begin
insert @ta select 上層業務 from tb where 部門=@name and 部門!=上層業務
select @name=上層業務 from tb where 部門=@name and 部門!=上層業務
end
return
end
select * from dbo.test_f('A')
刪除:
drop function test_f
drop table tb
上層業務
--------------------
B
C
D
(所影響的行數為 3 行)
(轉自:http://blog.csdn.net/jackeyabc/archive/2007/03/19/1533775.aspx)
但是可以從部門到上層業務,卻不知道怎麼修改成為從上層業務到部門.所以最終沒有採用