6,129
社区成员
发帖
与我相关
我的任务
分享
Create table Storage_Depository
(
DID varchar(50) not null primary key,
DName varchar(50) not null,
PID varchar(50) null
)
insert into Storage_Depository(DID,DName,PID)
select 'A','A仓库',null
union all
select 'A-1','A-1仓库','A'
union all
select 'A-2','A-2仓库','A'
union all
select 'A-1-1','A-1-1仓库','A-1'
union all
select 'B','B仓库',null
;
with w_Storage_Depository as
(
select DID,DName,PID,0 as lev,paths=cast(DID as nvarchar(1000))
from Storage_Depository where DID='A'
union all
select A.DID,A.DName,A.PID,B.lev + 1
,paths=cast(b.paths+'\'+a.DID as nvarchar(1000))
from Storage_Depository A,w_Storage_Depository B
where A.PID=B.DID
)
select *
from w_Storage_Depository
order by paths
/*
DID DName PID lev paths
-------------------------------------------------- -------------------------------------------------- -------------------------------------------------- ----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
A A仓库 NULL 0 A
A-1 A-1仓库 A 1 A\A-1
A-1-1 A-1-1仓库 A-1 2 A\A-1\A-1-1
A-2 A-2仓库 A 1 A\A-2
(4 行受影响)
*/
Create table Storage_Depository
(
DID varchar(50) not null primary key,
DName varchar(50) not null,
PID varchar(50) null
)
insert into Storage_Depository(DID,DName,PID)
select 'A','A仓库',null
union all
select 'A-1','A-1仓库','A'
union all
select 'A-2','A-2仓库','A'
union all
select 'A-1-1','A-1-1仓库','A-1'
union all
select 'B','B仓库',null
;
with w_Storage_Depository as
(
select DID,DName,PID,0 as lev,paths=cast(DID as nvarchar(1000))
from Storage_Depository where DID='A'
union all
select A.DID,A.DName,A.PID,B.lev + 1
,paths=cast(b.paths+'\'+a.DID as nvarchar(1000))
from Storage_Depository A,w_Storage_Depository B
where A.PID=B.DID
)
select a.* ,mark=case when b.PID is not null then '' else 'N' end
from w_Storage_Depository a
left join w_Storage_Depository b on a.DID=b.PID
order by a.paths
/*
DID DName PID lev paths mark
-------------------------------------------------- -------------------------------------------------- -------------------------------------------------- ----------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----
A A仓库 NULL 0 A
A A仓库 NULL 0 A
A-1 A-1仓库 A 1 A\A-1
A-1-1 A-1-1仓库 A-1 2 A\A-1\A-1-1 N
A-2 A-2仓库 A 1 A\A-2 N
(5 行受影响)
*/