SQL遞迴查詢

2021-04-18 23:42:27 字數 1333 閱讀 1595

create table t

(bid int,   p_bid      int)

insert into t

select 1,         null  union all

select 2,           1   union all

select 3,           1   union all

select 4,           3   union all

select 5,           4   union all

select 6,           5   union all

select 7,           1   union all

select 8,           2

create function dbo.aa(@parent int)

returns @t table(p_bid int,bid int,level int)

asbegin

declare @level int

set @level=1

insert into @t

select p_bid,bid,@level from t where p_bid=@parent

while @@rowcount>0

begin

set @level=@level+1

insert into @t

select a.p_bid,a.bid,@level

from t a,@t b

where a.p_bid=b.bid

and b.level=@level-1

endreturn

endgo

select space(level*5)+cast(bid as varchar),* from dbo.aa(1)

----------------------

with

showtree(

id) as

(

select

id from

dbo.

clients where

id=8

union all

select

clients.

id from

showtreeass

inner

join

clients on

s.id =

clients.

parent_id

)select

distinct

(id)

from

showtree

遞迴查詢SQL

lz需要的修改自己為對應的,csdn sqlserve大版主 鄒建 我轉貼並且完善一下 測試資料 create table tb id char 3 pid char 3 name nvarchar 10 insert tb select 001 null 山東省 union all select ...

SQL 遞迴查詢

create proc proc tree node int asbegin declare i int set i 0 set nocount on drop table res create table res node int,child int,weight int,op int inser...

sql遞迴查詢

有兩個表,a 部門表,儲存部門id 名稱 上級部門 b表 儲存部門員工表 id 姓名 部門id 現在我希望通過一條sql語句取得所有頂級部門下的員工 包含下級部門的員工 drop table dept create table dept dept id varchar 5 up id varchar...