日期:2014-05-18  浏览次数:20512 次

问个联合查询和字符串拼接的问题
需求是这样的,一张作者author表,一张book表:
author表                           book
------               -----
id       authorname         id       bookname       writerid
1         writer1               1         book1a           1
2         writer2               2         book1b           1
                                      3         book1c           1
                                      4         book2a           2
                                      5         book2b           2
我的存储过程该怎么写才能得到如下的查询结果:
id       authorname       bookname
1         writer1             book1a;book1b;book1c
2         writer2             book2a;book2b
前面不小心结贴了:
http://community.csdn.net/Expert/topic/5746/5746872.xml?temp=.1509058


------解决方案--------------------
联接查询不是问题,字符串合并可以参考这个:
--生成测试数据
create table 表(部门 int,人员 varchar(20))
insert into 表 select 1, '张三 '
insert into 表 select 1, '李四 '
insert into 表 select 1, '王五 '
insert into 表 select 2, '赵六 '
insert into 表 select 2, '邓七 '
insert into 表 select 2, '刘八 '
go

--创建用户定义函数
create function f_str(@department int)
returns varchar(8000)
as
begin
declare @ret varchar(8000)
set @ret = ' '
select @ret = @ret+ ', '+人员 from 表 where 部门 = @department
set @ret = stuff(@ret,1,1, ' ')
return @ret
end
go


--执行
select 部门,人员=dbo.f_str(部门) from 表 group by 部门 order by 部门
go

--输出结果
/*
部门 人员
---- --------------
1 张三,李四,王五
2 赵六,邓七,刘八
*/


--删除测试数据
drop function f_str
drop table 表
go
------解决方案--------------------
---创建自定义函数
Create Function Fn_Merge(@ID Int)
Returns Varchar(1000)
As
Begin
Declare @sql Varchar(1000)
Set @sql= ' '
Select @sql=@sql+ ', '+[bookname] From book Where Writerid=@ID
Return Stuff(@sql,1,1, ' ')
End
Go

---调用自定义函数查询结果
Select
ID,
authorname,
bookname=(Select dbo.Fn_Merge(writerid) From book Where writerid=A.ID Group By writerid)
From author As A