if object_id(
'[ta]'
)
is
not
null
drop
table
[ta]
go
create
table
ta([id]
int
,[
name
] nvarchar(4),[parentid] nvarchar(2))
go
insert
into
ta
select
1,
'河北省'
,
'0'
union
all
select
2,
'邢台市'
,
'1'
union
all
select
3,
'石家莊市'
,
'1'
union
all
select
4,
'張家口市'
,
'1'
union
all
select
5,
'南宮'
,
'2'
union
all
select
6,
'壩上'
,
'4'
union
all
select
7,
'任縣'
,
'2'
union
all
select
8,
'清河'
,
'2'
union
all
select
9,
'河南省'
,
'0'
union
all
select
10,
'新鄉市'
,
'9'
union
all
select
11,
'aaa'
,
'10'
union
all
select
12,
'bbb'
,
'10'
go
--start
;
with
district
as
(
select
*
from
ta
where
[
name
]=n
'河北省'
union
all
select
a.*
from
ta a,district b
where
a.parentid=b.id
)
select
*
from
district
--result:
/*
id
name
parentid
----------- ---- --------
1 河北省 0
2 邢台市 1
3 石家莊市 1
4 張家口市 1
6 壩上 4
5 南宮 2
7 任縣 2
8 清河 2
*/
上面**可以還不夠清晰 給多乙個例子
with district
--查詢列
(pid, fdepartmentname,fstate, ffathername) as
--父表
(select pid, fdepartmentname,fstate,convert(nvarchar(50), '') as ffathername from dbo.t_department where (fparentuserid is null or fparentuserid=0)
union all
--子表(注意是b的fdepartmentname)
select a.pid, a.fdepartmentname,a.fstate,b.fdepartmentname as ffathername from dbo.t_department as a
--關係
inner join district as b on a.fparentuserid = b.pid)
--查詢
select pid, fdepartmentname,fstate, ffathername
from district as c
資料庫遞迴查詢
今天工作看同事 用到了start with.connect by prior,不知道什麼意思,查詢了一些資料,以下是比較好理解的。oracle中的select語句可以用start with.connect by prior子句實現遞迴查詢,connect by 是結構化查詢中用到的,其基本語法是 s...
關於資料庫的遞迴查詢
1 oracle 以scott.emp表舉例 empno是人員編號,mgr是上級領導 也就是上級人員編碼 1 從上到下查詢 該查詢查詢員工jones下屬所有的員工 select emp.from emp start with ename jones connect by mgr prior empn...
遞迴查詢資料庫分銷上級
太陽線為準 團隊中所有的uid 一般情況最多10個 關於向上去找,還是向下去找,這裡取個巧 先比較下他們的uid大小,uid大的一定是後面註冊上來的 所以,以uid為大的來向上查詢 public function team tree uid,level 1 this team tree parent...