日期:2014-05-17 浏览次数:20461 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-12-05 15:33:30
-- 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('tempdb.dbo.#huang') is not null drop table #huang
go
create table #huang([col] varchar(1))
insert #huang
select 'a' union all
select 'b' union all
select 'c' union all
select 'd'
--------------开始查询--------------------------
select DISTINCT
stuff((select ','+col from #huang b
for xml path('')),1,1,'') 'col'
from #huang a
----------------结果----------------------------
/*
col
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
a,b,c,d
*/
if object_id('tb') is not null
drop table tb
go
create table tb([col] varchar(1))
insert tb
select 'a' union all
select 'b' union all
select 'c' union all
select 'd'
go
declare @t varchar(100)
select @t = ISNULL(@t,'') + ','+col
from tb a
select stuff(@t,1,1,'')
/*
a,b,c,d
*/
create table #table(name varchar(20))
insert into #table
select 'a' union all
select 'b' union all
select 'c' union all
select 'd'
select STUFF((
select ','+name from #table for xml path('')),1,1,'')
---------------------------------------------------------------------------------------