原贴:
http://community.youkuaiyun.com/Expert/topic/4790/4790673.xml?temp=.4949304
已知表A:
ID DESC
1 a
1 b
2 c
3 d
2 e
要得到表B的结构如下
ID Desc
1 a;b
2 c;e
3 d
也就是说ID相同的话,我要把DESC的内容加到一起
--解决办法:
1: 在SQL server 2000 中一般定义函数处理,(具体略)
2: 在SQL server 2005 中可以定义托管代码CLR处理.
方法如下:
--可以利用.net 2005 创建一个拖管函数,如下:
--1: .net 部分
using System;
using System.Data;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.IO;
using System.Text;
[Serializable]
[SqlUserDefinedAggregate(
Format.UserDefined, //使用UserDefined 序列化格式
IsInvariantToNulls = true, //聚合是否与空值有关
IsInvariantToDuplicates = false, //聚合是否与重复值有关
IsInvariantToOrder = false, //聚合是否与顺序有关
MaxByteSize = 8000) //聚合实例的最大大小(以字节为单位)
]
public class Concatenate : IBinarySerialize
{
/// <summary>
/// 定义变量
/// </summary>
private StringBuilder intermediateResult;
/// <summary>
/// 初始化
/// </summary>
public void Init()
{
this.intermediateResult = new StringBuilder();
}
/// <summary>
/// 如果某一个字符不为空,用";"追加
/// </summary>
/// <param name="value"></param>
public void Accumulate(SqlString value ) //symbol
{
if (value.IsNull)
{
return;
}
this.intermediateResult.Append(value.Value).Append(';');
}
/// <summary>
/// 合并字符
/// </summary>
/// <param name="other"></param>
public void Merge(Concatenate other)
{
this.intermediateResult.Append(other.intermediateResult);
}
/// <summary>
/// 处理最后的","
/// </summary>
/// <returns></returns>
public SqlString Terminate()
{
string output = string.Empty;
//删除最后的","
if (this.intermediateResult != null
&& this.intermediateResult.Length > 0)
{
output = this.intermediateResult.ToString(0, this.intermediateResult.Length - 1);
}
return new SqlString(output);
}
public void Read(BinaryReader r)
{
intermediateResult = new StringBuilder(r.ReadString());
}
public void Write(BinaryWriter w)
{
w.Write(this.intermediateResult.ToString());
}
}
---2: 数据库部分
----创建创建包含类元数据和托管代码的托管应用程序模块,将其作为 SQL Server 实例中的对象。
CREATE ASSEMBLY SQL_Aggregate FROM 'D:/IISWebRoot/SQLCLR/SQLFunction/SQLFunction/bin/Debug/SQLFunction.dll'
GO
CREATE AGGREGATE SQL_Aggregate (@input nvarchar(200)) RETURNS nvarchar(max)
EXTERNAL NAME SQL_Aggregate.Concatenate
--测试环境
create table tb(ID int,[desc] varchar(10))
insert into tb
select 1,'a'
union all select 1,'b'
union all select 2,'c'
union all select 3,'d'
union all select 2,'e'
go
--调用
select id,dbo.SQL_Aggregate([desc])
from tb
group by id
--结果
/*
ID Desc
------- ----------
1 a;b
2 c;e
3 d
(3 行受影响)
*/
--结论
--在SQL server 2005 自定义该聚合函数后,以后均可以使用该自定义聚合函数,实现数据合并.
--删除环境
drop table tb
drop AGGREGATE SQL_Aggregate
drop ASSEMBLY SQL_Aggregate