表project
pid 项目编号
pname 项目名称
现在表project里有如下数据
123 AAA
456 BBB
表detail
detailid 编号
pid 对应的项目名称
pp 品牌
表detail里有如下数据
1 123 DEll
2 123 IBM
3 456 TCl
向得到的结果集是这样的
项目名称 对应的品牌
AAA DEll,IBM
BBB TCL
也就是通过一条语句得到2个字段
一个是项目名称(这个简单)
还有一个就是这个项目下对应的品牌的字符串相加 就好像(DEll,IBM)
望高手指点
=================================
--测试环境
Create table project(pid int,pname varchar(10))
insert into project select 123,'AAA'
union all select 456,'BBB'
Create table detail(detailid int identity(1,1),pid int,pp varchar(10))
insert into detail select 123,'DEll'
union all select 123,'IBM'
union all select 456,'TCl'
--建函数
CREATE function F_GETSTR(@pid int)
returns varchar(200)
as
begin
declare @return varchar(200)
set @return=''
select @return=@return+','+pp+'' from detail
where pid=@pid
set @return=stuff(@return,1,1,'')
return @return
end
--查询
select 项目名称=(select pname from project where pid=A.pid),
对应的品牌=dbo.F_GETSTR(pid)
from detail A
group by pid
--结果
项目名称 对应的品牌
------- ---------
AAA DEll,IBM
BBB TCl
(所影响的行数为 2 行)
--删除测试环境
Drop table project,detail
Drop function F_GETSTR