新建表:
![]()
Code
create table StudentCourse (NO varchar(10),CourseName varchar(10))
insert StudentCourse
select '2009001', '数学' union all
select '2009001', '英语' union all
select '2009002', '数学' union all
select '2009002', '语文' union all
select '2009002', '英语' union all
select '2009003', '英语'
写函数:
![]()
Code
CREATE FUNCTION dbo.f_StudentCourse(@NO varchar(10))
RETURNS varchar(200)
AS
BEGIN
DECLARE @str varchar(200)
SET @str = ''
SELECT @str = @str + '、' + CourseName FROM StudentCourse WHERE NO=@NO
RETURN STUFF(@str, 1, 1, '')
END查询语句:
SELECT NO, CourseName=dbo.f_StudentCourse(NO) FROM StudentCourse GROUP BY NO
查询结果如下所示:
![]()