说明:本文依据网络转载整理而成,因为时间关系,其中原理暂时并未深入研究,只是整理备份留个记录而已。

目标:在SQL Server中自定义聚合函数,在Group BY语句中 ,不是单纯的SUM和MAX等运算,可以加入拼接字符串。

环境:

1:Sqlserver 2008 R2

2:Visual Studio 2013

第一部分:

.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,string contChar) //symbol
{
if (value.IsNull)
{
return;
}
this.intermediateResult.Append(value.Value).Append(contChar);
}
/// <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());
}
}

编译生成DLL,注意:SqlServer 2008 R2  不支持.Net Framework 4.5 ,所以生成dll的时候选在.net framework 3.5

第二步:启用数据库对CLR支持的配置

EXEC sp_configure 'clr enabled', 1
RECONFIGURE WITH OVERRIDE
GO

第三步:加载CLR程序集并创建自定义函数

USE Test   --选择数据库
CREATE ASSEMBLY SQL_Aggregate FROM 'E:\WorkSpace\LetMeTry\WindowsFormsApplication2\SqlCustomFunction\bin\Debug\SqlCustomFunction.dll' --生成的DLL路径
GO
CREATE AGGREGATE SQL_Aggregate (@input nvarchar(200),@contChar nvarchar(1)) RETURNS nvarchar(max)
EXTERNAL NAME SQL_Aggregate.Concatenate

第四步:测试

USE Test

--创建测试数据
create table tb(ID int,Name varchar(10))
insert into tb
select 1,'a'
union all select 1,'b'
union all select 2,'c'
union all select 2,'e'
union all select 3,'d'
go --自定义聚合函数使用例子(第二个参数为拼接字符串的连接符)
select id,dbo.SQL_Aggregate([Name],'+') AS Test
from tb
group by id

  

SQL Server 自定义聚合函数的更多相关文章

  1. SQL server 数据库 ——聚合函数(一列 多行,值类型)

    聚合函数 5种函数: 1.max最大值   select max(price) from car where code='c024' 2.min最小值   select * from car wher ...

  2. sql server中用聚合函数查询退休人的开销信息

    1创建表 create database Mathgouse MathgoCREATE TABLE A(ID INT PRIMARY KEY IDENTITY,--自增主键ID_CARD VARCHA ...

  3. sql server自定义函数学习笔记

    sql server中函数分别有:表值函数.标量函数.聚合函数.系统函数.这些函数中除系统函数外其他函数都需要用户进行自定义. 一.表值函数 简单表值函数 创建 create function fu_ ...

  4. 13、SQL Server 自定义函数

    SQL Server 自定义函数 在SQL Server中不仅可以使用系统函数(如:聚合函数,字符串函数,时间日期函数等)还可以根据需要自定义函数. 自定义函数分为标量值函数和表值函数. 其中,标量值 ...

  5. 也来谈谈SQL SERVER 自定义函数~

    在使用SQL SERVER 数据库的时候,函数大家都应该用过,简单的比如 系统聚合函数 Sum(),Max() 等等.但是一些初学者编写自定义函数的时候,经常问起什么是表值函数,什么是标量值函数. 表 ...

  6. sql server 自定义函数的使用

    sql server 自定义函数的使用 自定义函数 用户定义自定义函数像内置函数一样返回标量值,也可以将结果集用表格变量返回 用户自定义函数的类型: 标量函数:返回一个标量值 表格值函数{内联表格值函 ...

  7. SQL Server 自定义函数(Function)——参数默认值

    sql server 自定义函数分为三种类型:标量函数(Scalar Function).内嵌表值函数(Inline Function).多声明表值函数(Multi-Statement Functio ...

  8. SQL Server 内置函数、临时对象、流程控制

    SQL Server 内置函数 日期时间函数 --返回当前系统日期时间 select getdate() as [datetime],sysdatetime() as [datetime2] getd ...

  9. 应用C#和SQLCLR编写SQL Server用户定义函数

    摘要: 文档阐述使用C#和SQLCLR为SQL Server编写用户定义函数,并演示用户定义函数在T-SQL中的应用.文档中实现的 Base64 编码解码函数和正则表达式函数属于标量值函数,字符串分割 ...

随机推荐

  1. StackGAN: Text to Photo-realistic Image Synthesis with Stacked Generative Adversarial Networks 论文笔记

    StackGAN: Text to Photo-realistic Image Synthesis with Stacked Generative Adversarial Networks  本文将利 ...

  2. Lua词汇约定

    Lua的标识符包含数字,字母以及下划线,数字不能作为标识符的开头. and break do else elseif end false for function goto if in local n ...

  3. php 一些经常用到的方法

    获取当前url地址 /** * 获取当前url * @author Red * @date * @return string */ function getRequestURL() { if (!is ...

  4. Oracle 11g r2 安装

    Help Center:http://docs.oracle.com/cd/E11882_01/install.112/e24326/toc.htm#i1011296 前提:linux需要安装图形化介 ...

  5. JavaScript使用XMLHttpRequest 發送GET/Post 請求

    <!DOCTYPE HTML> <html> <head> <title>Demo</title> <script type=&quo ...

  6. javax.servlet.http.HttpServlet was not found

    我们遇到的错误显示如下:   我们右击有错误提示的文件夹,如下:   我们点击"配置构建路径",如下:   我们再点击"添加库",如下:   我们选中上图中标出 ...

  7. nodejs向远程服务器发送post请求----融云Web SDK/客户端获取token

    最近要用到一个叫融云的及时通讯的SDK,在获取token这个步骤的时候有点卡顿,以防以后碰到类似的问题,再此记录一下. 客户端通过融云 SDK 每次连接服务器时,都需要向服务器提供 Token,以便验 ...

  8. <<软件测试实战>>读书笔记

    软件测试基础 软件的复杂度已经超越了人的理解能力 1. 虽然高抽象的层次语言,程序框架,程序库等提高了人的生产力,但是还是需要开发者深入理解细节,可以减少开发时间,但是无法减少开发者学习整个技术栈的时 ...

  9. SOAOffice和iWebOffice、NTKO的比较及其优势(转)

    http://www.cnblogs.com/liping13599168/articles/1681465.html SOAOffice和iWebOffice.NTKO的比较及其优势 近年来,市场上 ...

  10. GBDT算法原理深入解析

    GBDT算法原理深入解析 标签: 机器学习 集成学习 GBM GBDT XGBoost 梯度提升(Gradient boosting)是一种用于回归.分类和排序任务的机器学习技术,属于Boosting ...