--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