您现在的位置是:网站首页> 编程资料编程资料
sql server多行数据拼接的实例方法_MsSql_
2023-05-26
462人已围观
简介 sql server多行数据拼接的实例方法_MsSql_
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
相关内容
- SQL Server 游标语句 声明/打开/循环实例_MsSql_
- SQL Server 2012 安装图解教程(附sql2012下载地址)_MsSql_
- SQL Server控制语句的基本应用_MsSql_
- SQL Server的基本功能性语句介绍_MsSql_
- 关于SQL Server查询语句的使用_MsSql_
- mssql server 2012(SQL2012)各版本功能对比_MsSql_
- sql存储过程的使用和介绍_MsSql_
- SQLite数据库管理相关命令的使用介绍_MsSql_
- 基于SQL Server OS的任务调度机制详解_MsSql_
- 在SQL Server中实现最短路径搜索的解决方法_MsSql_
