我有3张包含记录的表
通过连接这3个表来编写用于从这3个表中检索数据的存储过程,如下图所示,我想要实现的目标是什么。结果应如下所示
所以我努力了但是我没有成功。帮助将受到高度赞赏
答案 0 :(得分:2)
您无法在连接中执行示例输出中显示的字符串连接类型。有两种方法可以解决这个问题。
如果您被指示使用存储过程,则使用前一种方法,否则后者将更有效。
create function dbo.GetProfessionList(@employeeid int) returns varchar(max)
as
begin
declare @prof varchar(50), @list varchar(max) = '';
declare foo cursor for
select G.Profession
from Groups G
join EmployeeGroups EG on EG.GroupID = G.GroupID
where EG.EmployeeID = @employeeid;
open foo;
fetch next from foo into @prof;
while @@FETCH_STATUS = 0
begin
set @list = @list + @prof + ', ';
fetch next from foo into @prof;
end
close foo;
deallocate foo;
--remove trailing comma
return LEFT(@list,LEN(@list) - 2);
end
select *, dbo.GetProfessionList(EmployeeID) as Profession
from Employee
答案 1 :(得分:2)
你的回答
Select E.EmployeeID, E.EmployeeName,
STUFF((SELECT ', ' + G.Profession
from EmployeeGroups EG
Inner Join Groups G on G.GroupId = EG.GroupId
where E.EmployeeId = EG.EmployeeId
FOR XML PATH('')
), 1, 1, '') Profession
From Employee E;
我希望它对你有用。