日期:2014-05-16 浏览次数:20421 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-02-27 07:39:46
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([领导] varchar(2),[下属] varchar(2))
insert [huang]
select 'AA','BB' union all
select 'AA','CC' union all
select 'BB','DD' union all
select 'BB','EE' union all
select 'CC','FF' union all
select 'CC','GG' union all
select 'DD','HH' union all
select 'DD','II' union all
select 'EE','JJ' union all
select 'EE','KK'
--------------开始查询--------------------------
DECLARE @a VARCHAR(10)
SET @a='BB'
;WITH cte AS (
select *
from [huang]
WHERE 领导=@a
UNION ALL
SELECT a.领导,a.下属
FROM huang a INNER JOIN cte b ON b.下属=a.领导
),ym AS (
SELECT DISTINCT name
FROM (SELECT 领导 name FROM cte
UNION SELECT 下属 FROM cte)a)
select DISTINCT stuff((select ','+name from ym b
for xml path('')),1,1,'') 'name'
from ym a
----------------结果----------------------------
/*
name
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
BB,DD,EE,HH,II,JJ,KK
*/
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-02-27 07:39:46
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if