日期:2014-05-16 浏览次数:20741 次
----------------------------------------------------------------
-- Author :DBA_HuangZJ(发粪涂墙)
-- Date :2014-03-05 17:10:55
-- Version:
-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64)
-- Apr 2 2010 15:48:46
-- Copyright (c) Microsoft Corporation
-- Enterprise 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]([a] nvarchar(4),[b] nvarchar(4))
insert [huang]
select 'TA','SH' union all
select 'TA','BJ' union all
select 'TA','HN' union all
select 'TB','WX' union all
select 'TB','SG'
--------------生成数据--------------------------
--2005
select a.[a],
stuff((select ','+[b] from [huang] b
where b.[a]=a.[a]
for xml path('')),1,1,'') [b]
from [huang] a
group by a.[a]
--2000
go
if object_id('F_Str') is not null
drop function F_Str
go
create function F_Str(@Col1 nvarchar(100))
returns nvarchar(100)
as
begin
declare @S nvarchar(100)
select @S=isnull(@S+',','')+[b] from [huang] where [a]=@Col1
return @S
end
go
Select distinct [a],[b]=dbo.F_Str([a]) from [huang]
go
----------------结果----------------------------
/*
a b
---- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
TA SH,BJ,HN
TB WX,SG
(2 row(s) affected)
a b
---- ----------------------------------------------------------------------------------------------------
TA SH,BJ,HN
TB WX,SG
*/