日期:2014-05-17 浏览次数:20456 次
create table ta(id int,name varchar(10))
insert into ta
select 1,'a'
union all select 1,'b'
union all select 1,'c'
union all select 1,'d'
union all select 1,'e'
select a.id,
(select ''+name from ta b
where b.id=a.id
for xml path('')) 'name'
from ta a
group by a.id
/*
id name
---------------------
1 abcde
*/
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-10-12 09:56:50
-- Version:
-- Microsoft SQL Server 2014 (CTP1) - 11.0.9120.5 (X64)
-- Jun 10 2013 20:09:10
-- Copyright (c) Microsoft Corporation
-- Enterprise Evaluation Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([id] int,[name] varchar(1))
insert [huang]
select 1,'a' union all
select 1,'b' union all
select 1,'c' union all
select 1,'d' union all
select 1,'e'
--------------开始查询--------------------------
select a.id,REPLACE(
stuff((select ','+name from [huang] b
where b.ID=a.ID
for xml path('')),1,1,''),',','') 'name'
from [huang] a
group by a.ID
----------------结果----------------------------
/*
id name
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 abcde
*/
create table test(id int,name varchar)
insert into test
select '1','a'
union all select '2','b'
union all select '3','c'
union all select '4','d'
union all select '5','e'
select * from test;