SQL Server使用STUFF,Function

时间:2014-10-21 07:52:39

标签: sql-server

我有两张表departmentemployees。我有一项任务,使用表值函数显示属于同一行中给定部门的员工。

实施例

[clothes] [mike, aaron, shannon, etc]
[games]   [charles, darwin, bob, etc]

由于我是SQL Server新手,我尝试使用带有函数的游标,但游标很难理解和使用。我试图使用功能的东西,但有错误。我希望有人可以帮助我

ALTER FUNCTION cursorit2()
RETURNS TABLE
AS
    RETURN
      (SELECT c.dept_name,
              STUFF((SELECT ',' + s.emp_fname + s.emp_lname
                     FROM   Employee s
                     WHERE  c.dept_no = s.dept_no
                     FOR XML PATH('')), 1, 1, '')
       FROM   Department AS c
              INNER JOIN Employee AS s
                      ON s.dept_no = c.dept_no) 

1 个答案:

答案 0 :(得分:1)

ALTER FUNCTION cursorit2()
RETURNS TABLE
AS
    RETURN
      (SELECT c.dept_name,
              STUFF((SELECT ',' + s.emp_fname + s.emp_lname
                     FROM   Employee s
                     WHERE  c.dept_no = s.dept_no
                     FOR XML PATH('')), 1, 1, '') as yourColumnName --add name here
       FROM   Department AS c
              INNER JOIN Employee AS s
                      ON s.dept_no = c.dept_no)