日期:2014-05-17 浏览次数:20730 次
if not object_id('Tab') is null
drop table Tab
Go
Create table Tab([Col1] int,[Col2] nvarchar(1))
Insert Tab
select 1,N'a' union all
select 1,N'b' union all
select 1,N'c' union all
select 2,N'd' union all
select 2,N'e' union all
select 3,N'f'
Go
--合并表:
--SQL2000用函数:
if object_id('F_Str') is not null
drop function F_Str
go
create function F_Str(@Col1 int)
returns nvarchar(100)
as
begin
declare @S nvarchar(100)
select @S=isnull(@S+',','')+Col2 from Tab where Col1=@Col1
return @S
end
go
Select distinct Col1,Col2=dbo.F_Str(Col1) from Tab
go
--2005 xml
select
Col1,
Col2=stuff((select ','+ltrim(Col2)
from Tab
where Col1=t.Col1 for xml path('')), 1, 1, '')
from Tab AS t
group by Col1
------解决方案--------------------
with t
as
(
select b.ppid,a.pid,b.name
from Project a
inner join ProParticipate b
on a.pid=b.pid
)
select PPid,Pid,
name=stuff((select ','+ltrim(name) from t b where a.pid=b.pid for xml path('')), 1, 1, '')
from t a
------解决方案--------------------