1.表结构idtypeproductCode1铅笔00012铅笔00023铅笔00034钢笔00045钢笔00056钢笔00047圆珠笔00078圆珠笔00089圆珠笔00072.自定义函数fun复制代码 代码如下: GO/****** Object: UserDefinedFunction [dbo].[fun] Script Date: 11/22/2011 16:09:45 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCreate function [dbo].[fun](@type nvarchar(10))returns nvarchar(200)asbegin declare @re nvarchar(200) declare @code nvarchar(200) set @re='' set @code='' select @re=@re+productCode+',' from T where type=@type group by productCode select @re=left(@re, len(@re)-1) return @reend
3.查询语句select type,dbo.fun(type) from (select distinct type from T) A结果:钢笔 0004,0005铅笔 0001,0002,0003圆珠笔 0007,0008