日期:2014-05-17 浏览次数:20540 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-11-12 15:23:42
-- 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]([name] varchar(5),[age] int)
insert [huang]
select 'jack',20 union all
select 'tom',30 union all
select 'nancy',20
--------------开始查询--------------------------
select a.[age],
stuff((select ','+[name] from [huang] b
where b.[age]=a.[age]
for xml path('')),1,1,'') 'name'
from [huang] a
WHERE [age]=20
group by a.[age]
----------------结果----------------------------
/*
age name
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
20 jack,nancy
*/
--創建數據
create table #temp([name] varchar(5),[age] int)
insert #temp
select 'jack',20 union all
select 'tom',30 union all
select 'nancy',20
--开始查询
SELECT stuff((select ','+[name] from #temp WHERE [age]=20 for xml path('')),1,1,'') [name]
create table #tb([name] varchar(5),[age] int)
insert #tb select 'jack',20 union all
select 'tom',30 union all
select 'nancy',20
select * from #tb
declare @sql varchar(200)=''
select @sql =@sql+','+name from #tb where age ='20'
select stuff(@sql ,1,1,'')
drop table #tb
--drop t