SQL2005的CTE

use test
go
if object_id ( ' Tempdb..#T ' ) is not null
drop table #T
create table #T(ID int ,Name nvarchar ( 100 ),parentID int )
insert #T select 1 , ' A ' , 0
insert #T select 2 , ' B ' , 1
insert #T select 3 , ' C ' , 1
insert #T select 4 , ' D ' , 3
insert #T select 5 , ' E ' , 2

go

with t2(ID,Name,parentID,Ord,Lev)
as
(
select * ,Ord = cast ( right ( ' 0000 ' + rtrim (ID), 4 ) as nvarchar ( max )),Lev = cast ( 0 as int ) from #T where ParentID = 0
union all
select b. * ,Ord = a.Ord + cast ( right ( ' 0000 ' + rtrim (b.ID), 4 ) as nvarchar ( max )),Lev = cast (a.Lev + 1 as int ) from #Tb join t2a on b.ParentID = a.ID
)
select 顯示 = replicate ( char ( 9 ),lev) + Name from T2 order by ord option (maxrecursion 0 ) -- 用空格替換制表符時用space(lev*2)/replicate(char(9),lev)

/**/ /*
顯示
---------------------------------
A
B
E
C
D

(5個資料列受到影響)
*/



;
with t2
as
(
select * ,Ord = cast (Name as nvarchar ( max )),lev = 0 from #T where ParentID = 0
union all
select b. * ,Ord = cast (a.Ord + char ( 9 ) + b.Name as nvarchar ( max )),a.lev + 1 from #Tb join t2a on b.ParentID = a.ID
)
select
[ 顯示 ] = Ord
from
T2
order by ord
option (maxrecursion 0 )
/**/ /*

顯示
--------------------
A
AB
ABE
AC
ACD

(5個資料列受到影響)

*/


-- 2005多次调用连接时:
/**/ /*
;withT(COl)--可指定列名也可不指定
as
(......)
,T2(Co)
as
(......)
select*fromT1ajoinT2bona.Col=b.COl
*/



你可能感兴趣的:(sql2005)