日期:2014-05-17 浏览次数:20680 次
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2013-11-20 17:53:40
-- Verstion:
-- Microsoft SQL Server 2012 - 11.0.2100.60 (X64)
-- Feb 10 2012 19:39:15
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([ID] int,[IDs] varchar(7),[Name] varchar(3))
insert [tb]
select 1,'.1.2.3.','张1' union all
select 2,'.3.','张2' union all
select 3,'.2.3.','张3' union all
select 4,'.1.3.','张4'
--------------开始查询--------------------------
SELECT
[id],ids,name,
idsname=stuff((select '.'+LTRIM(Name) from tb WHERE CHARINDEX('.'+LTRIM(id)+'.','.'+a.ids+'.')>0 for xml path('')), 1, 1, '')
FROM
TB a
GROUP BY
[id],ids,name
----------------结果----------------------------
/* id ids name idsname
----------- ------- ---- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 .1.2.3. 张1 张1.张2.张3
2 .3. 张2 张3
3 .2.3. 张3 张2.张3
4 .1.3. 张4 张1.张3
*/
if object_id('[tb]') is not null drop table [tb]
go
create&