当前位置: 代码迷 >> Sql Server >> 求1SQL语句,关于省市区这样树状结构的
  详细解决方案

求1SQL语句,关于省市区这样树状结构的

热度:25   发布时间:2016-04-24 10:15:08.0
求一SQL语句,关于省市区这样树状结构的.
数据如下:
表名: Area
id                   name                                               pid
-------------------- -------------------------------------------------- --------------------
3                    河北省                                                0
147                  邢台市                                                3
149                  桥东区                                                147
150                  桥西区                                                147
151                  邢台县                                                147
152                  临城县                                                147
153                  内丘县                                                147
154                  柏乡县                                                147
155                  隆尧县                                                147

根据网上的资料我已实现 "查询树状结构某节点的上级所有根节点" 和 "--查询树状结构某节点下的所有子节点"


但我想要这样的查询效果:
1、
id              name 
3 河北省
147 河北省/邢台市
149 河北省/邢台市/桥东区
150 河北省/邢台市/桥西区

就是某一id下面的所有数据,并且name可以这样串起来,

2、某一id的上级数据,name也可以串起来。



------解决方案--------------------
如果需要筛选,在最后语句中加where即可
----------------------------------------------------------------
-- Author  :DBA_HuangZJ(發糞塗牆)
-- Date    :2014-07-31 11:22:21
-- Version:
--      Microsoft SQL Server 2012 - 11.0.5058.0 (X64) 
-- May 14 2014 18:34:29 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[Area]
if object_id('[Area]') is not null drop table [Area]
go 
create table [Area]([id] int,[name] varchar(6),[pid] int)
insert [Area]
select 3,'河北省',0 union all
select 147,'邢台市',3 union all
select 149,'桥东区',147 union all
select 150,'桥西区',147 union all
select 151,'邢台县',147 union all
select 152,'临城县',147 union all
select 153,'内丘县',147 union all
  相关解决方案