建立地区表 , 且插入模拟的几条数据
1 CREATE TABLE City
2 (
3 id INT PRIMARY KEY IDENTITY(100, 10),
4 name VARCHAR(20) NOT NULL,
5 parentid INT NOT NULL
6 )
7
8 INSERT INTO City VALUES('北京', -1)
9 INSERT INTO City VALUES('东城', 100)
10 INSERT INTO City VALUES('西城', 100)
11 INSERT INTO City VALUES('丰台', 100)
12 INSERT INTO City VALUES('刘家窑', 130)
只需下面这样:
WITH cate AS
(
SELECT * FROM City WHERE id = 180
UNION ALL
SELECT A.* FROM City A JOIN cate B ON A.id = B.parentid
)
SELECT * FROM cate
就可以得到刘家窑的目录信息,如下:
180 刘家窑 130
130 丰台 100
100 北京 -1