--create table tb(id int,name nvarchar(30),pid int)
--insert into tb
--select 1,'遼寧省',0 union all
--select 2,'瀋陽市',1 union all
--select 3,'大連市',1 union all
--select 4,'大東區',2 union all
--select 5,'瀋河區',2 union all
--select 6,'鐵西區',2
with
district as
(
-- 獲得第一個結果集,並更新最終結果集
select * from tb where name= N'遼寧省' --定位點成員
union all
-- 下面的select語句首先會根據從上一個查詢結果集中獲得的id值來查詢parent_id
-- 字段的值,然後district就會變當前的查詢結果集,並繼續執行下面的select 語句
-- 如果結果集不爲null,則與最終的查詢結果合併,同時用合併的結果更新最終的查
-- 詢結果;否則停止執行。最後district的結果集就是最終結果集。
select a.* from tb a, district b--遞歸成員
where a.pid = b.id
--1.將 CTE 表達式拆分爲定位點成員和遞歸成員。
--
--
--2.運行定位點成員,創建第一個調用或基準結果集 (T0)。
--
--
--3.運行遞歸成員,將 Ti 作爲輸入,將 Ti+1 作爲輸出。
--
--
--4.重複步驟 3,直到返回空集。
--
--
--5.返回結果集。這是對 T0 到 Tn 執行 UNION ALL 的結果。
)
select * from district
--select * into district from tb where name=N'遼寧省'
--insert into district
--select a.* from tb a,district b where a.pid=b.id
--select * from district