用遞迴處理樹型結構 表結構

2021-04-09 08:46:49 字數 2621 閱讀 8192

/*

用遞迴處理樹型結構(表結構)

遞迴求城市,從小到大的,或從大到小。*/

/*等依次類推得目錄樹結構

我想寫乙個函式 傳入部門id號後 馬上得到相應的 部門結構 如

輸入8得到的是市場部-東南市場-上海市

輸入9得到的是市場部-西北市場-北京市

輸入6得到的是市場部-西北市場

輸入3得到的是市場部

輸入1得到的是所有部門

*/--建立測試環境

create table tablea(deptid int,deptname nvarchar(100),parentid int)

insert into tablea

select 1,'所有部門',0 union all

select 2,'財務部', 1 union all

select 3,'市場部', 1 union all

select 4,'倉庫管理',1 union all

select 5,'東北市場',3 union all

select 6,'西北市場',3 union all

select 7,'東南市場',3 union all

select 8,'上海市', 7 union all

select 9,'北京市', 6

--建立函式

if exists (select * from dbo.sysobjects where id = object_id(n'[dbo].[alldept]') and xtype in (n'fn', n'if', n'tf'))

drop function [dbo].[alldept]

gocreate function alldept(@ideptid int)

returns nvarchar(1000)

asbegin

declare @vreturnvalue nvarchar(1000)

,@iparentid int

,@vcurrentdeptname nvarchar(200)

select @vreturnvalue=''

,@vcurrentdeptname=''

if(exists(select top 1 0 from tablea where deptid=@ideptid and parentid=0))

begin

select @vreturnvalue =@vreturnvalue+deptname+'-'

from tablea  

where parentid<>0

return (@vreturnvalue)

endif(exists(select top 1 0 from tablea where deptid=@ideptid and parentid=1))

begin

select @vreturnvalue=@vreturnvalue+deptname

from tablea where deptid=@ideptid and parentid=1

--return (@vreturnvalue)

--set @vreturnvalue=@vreturnvalue+dbo.alldept(@iparentid)

endelse

begin             

select @iparentid=parentid

,@vcurrentdeptname=deptname

from tablea

where deptid=@ideptid

set @vreturnvalue=@vreturnvalue+@vcurrentdeptname+'-'+dbo.alldept(@iparentid)

--return (@vreturnvalue)

endreturn (@vreturnvalue)

endgo

set quoted_identifier off

goset ansi_nulls on

goselect *,dbo.alldept(deptid) alldeptname from tablea

select * from tablea

--顯示結果

deptid

deptname       alldeptname

1      所有部門

0     財務部-市場部-倉庫管理-東北市場-西北市場-東南市場-上海市-北京市-

2      財務部

1     財務部

3      市場部

1     市場部

4      倉庫管理

1     倉庫管理

5      東北市場

3     東北市場-市場部

6      西北市場

3     西北市場-市場部

7      東南市場

3     東南市場-市場部

8      上海市

7     上海市-東南市場-市場部

9      北京市

6     北京市-西北市場-市場部

--刪除測試環境

drop table tablea

drop table dbo.alldept

樹型結構遞迴 實體遞迴 JSON格式

下列 不能直接使用 create table dbo p category code varchar 36 not null primary key,parent code varchar 36 null,depth int null,name varchar 50 null go insert d...

樹型結構遞迴 實體遞迴 JSON格式

下列 不能直接使用 create table dbo p category code varchar 36 not null primary key,parent code varchar 36 null,depth int null,name varchar 50 null go insert d...

樹型表結構的查詢

connect by 是結構化查詢中用到的,其基本語法是 select from tablename start by cond1 connect by cond2 where cond3 簡單說來是將乙個樹狀結構儲存在一張表裡,比如乙個表中存在兩個字段 id,parentid那麼通過表示每一條記錄...