sql server多行数据拼接的实例方法
程序员文章站
2023-12-10 08:31:58
1.表结构id type productcode1 铅笔 00012 铅笔 00023 铅笔 ...
1.表结构
id type productcode
1 铅笔 0001
2 铅笔 0002
3 铅笔 0003
4 钢笔 0004
5 钢笔 0005
6 钢笔 0004
7 圆珠笔 0007
8 圆珠笔 0008
9 圆珠笔 0007
2.自定义函数fun
go
/****** object: userdefinedfunction [dbo].[fun] script date: 11/22/2011 16:09:45 ******/
set ansi_nulls on
go
set quoted_identifier on
go
create function [dbo].[fun](@type nvarchar(10))
returns nvarchar(200)
as
begin
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 @re
end
3.查询语句
select type,dbo.fun(type) from (select distinct type from t) a
结果:
钢笔 0004,0005
铅笔 0001,0002,0003
圆珠笔 0007,0008
id type productcode
1 铅笔 0001
2 铅笔 0002
3 铅笔 0003
4 钢笔 0004
5 钢笔 0005
6 钢笔 0004
7 圆珠笔 0007
8 圆珠笔 0008
9 圆珠笔 0007
2.自定义函数fun
复制代码 代码如下:
go
/****** object: userdefinedfunction [dbo].[fun] script date: 11/22/2011 16:09:45 ******/
set ansi_nulls on
go
set quoted_identifier on
go
create function [dbo].[fun](@type nvarchar(10))
returns nvarchar(200)
as
begin
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 @re
end
3.查询语句
select type,dbo.fun(type) from (select distinct type from t) a
结果:
钢笔 0004,0005
铅笔 0001,0002,0003
圆珠笔 0007,0008