假设mssql2000中, 有如下表: table Class class_No course_Name ----------------------------------- 0001 chinese 0001 math 0001 english 0002 chinese 0002 math 0003 english 如果要查询出下面这种格式的结果,如何实现?请指教,谢谢! 结果: class_No course_Name ------------------------------------------------ 0001 chinese, math, english 0002 chinese, math 0003 english 另外,如果要选出包含english的行,该如何操作? 搜索包含english的结果: class_No course_Name ------------------------------------------------ 0001 chinese, math, english 0003 english
create function [f_str] ( @id int ) returns nvarchar(1000) as begin declare @str nvarchar(1000) set @str = '' select @str = @str + ',' + cast(course_Name as nvarchar(20)) from tb_Class where class_No = @id set @str = right(@str , len(@str) - 1) return @str end go --建立函数成功,调用函数 select id class_No, course_Name= f_str(class_No) from tb_Class group by class_No