不多说了,说明后面是完整的代码,用来将字符串型的字段的各行的值拼成一个大字符串,也就是通常所说的Concat

例如有如下表dict

 ID  NAME  CATEGORY
 1 RED  COLOR 
 2 BLUE COLOR
 3 APPLE  FRUIT
 4 ORANGE FRUIT

执行SQL语句:select category,dbo.concatenate(name) as names from dict group by category.

得到结果表如下

 category  names
 COLOR REDBLUE 
 FRUIT  APPLEORANGE

如果觉得需要用逗号或分号或其他任何你想要的分隔符分开,可以修改下面的代码来实现。

在VS2005中,创建一个连接到目标库的SQL SERVER PROJECT,然后填加一个“聚合”,将下面的代码复制进去,编译后,部署即可,然后在SQL SERVER中的“可编程性”“函数”“聚合函数”中就可以看到该函数了。

using System;
using System.Data;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.IO;
using System.Text;

[Serializable]
[SqlUserDefinedAggregate(
    Format.UserDefined, //use clr serialization to serialize the intermediate result
    IsInvariantToNulls = true, //optimizer property
    IsInvariantToDuplicates = false, //optimizer property
    IsInvariantToOrder = false, //optimizer property
    MaxByteSize = 8000) //maximum size in bytes of persisted value
]
public class Concatenate : IBinarySerialize
{
    /// <summary>
    /// The variable that holds the intermediate result of the concatenation
    /// </summary>
    private StringBuilder intermediateResult;

/// <summary>
    /// Initialize the internal data structures
    /// </summary>
    public void Init()
    {
        this.intermediateResult = new StringBuilder();
    }

/// <summary>
    /// Accumulate the next value, not if the value is null
    /// </summary>
    /// <param name="value"></param>
    public void Accumulate(SqlString value)
    {
        if (value.IsNull)
        {
            return;
        }

this.intermediateResult.Append(value.Value);
    }

/// <summary>
    /// Merge the partially computed aggregate with this aggregate.
    /// </summary>
    /// <param name="other"></param>
    public void Merge(Concatenate other)
    {
        this.intermediateResult.Append(other.intermediateResult);
    }

/// <summary>
    /// Called at the end of aggregation, to return the results of the aggregation.
    /// </summary>
    /// <returns></returns>
    public SqlString Terminate()
    {
        string output = string.Empty;
        //delete the trailing comma, if any
        if (this.intermediateResult != null
            && this.intermediateResult.Length > 0)
        {
            output = this.intermediateResult.ToString(0, this.intermediateResult.Length );
        }

return new SqlString(output);
    }

public void Read(BinaryReader r)
    {
        intermediateResult = new StringBuilder(r.ReadString());
    }

public void Write(BinaryWriter w)
    {
        w.Write(this.intermediateResult.ToString());
    }
}

这里有几个比较重要的方法:Terminate,这个方法是聚合最后调用的方法,它返回最后的值。可以是SQL Server的任何标量;Accumulate,聚合每处理一行数据的时候都会调用一次,并将要处理的数据传给方法。可以在函数内部进行比如比较,合并之类的处理。

SQL SERVER 2005允许自定义聚合函数的更多相关文章

  1. SQL SERVER 2005允许自定义聚合函数-表中字符串分组连接

    不多说了,说明后面是完整的代码,用来将字符串型的字段的各行的值拼成一个大字符串,也就是通常所说的Concat 例如有如下表dict  ID  NAME  CATEGORY  1 RED  COLOR  ...

  2. 深入理解SQL Server 2005 中的 COLUMNS_UPDATED函数

    原文:深入理解SQL Server 2005 中的 COLUMNS_UPDATED函数 概述 COLUMNS_UPDATED函数能够出现在INSERT或UPDATE触发器中AS关键字后的任何位置,用来 ...

  3. 解密SQL SERVER 2005加密存储过程,函数

    在SQL SERVER 2005中必须用专用管理连接才可以查看过程过程中用到的表 EG:sqlcmd -A 1>use test 2>go 1>sp_decrypt 'p_testa ...

  4. sql server 2005中的分区函数用法(partition by 字段)

    分组取TOP数据是T-SQL中的常用查询, 如学生信息管理系统中取出每个学科前3名的学生.这种查询在SQL Server 2005之前,写起来很繁琐,需要用到临时表关联查询才能取到.SQL Serve ...

  5. SQL Server如何定位自定义标量函数被那个SQL调用次数最多浅析

    前阵子遇到一个很是棘手的问题,监控系统DPA发现某个自定义标量函数被调用的次数非常高,高到一个离谱的程度.然后在Troubleshooting这个问题的时候,确实遇到了一些问题让我很是纠结,下文是解决 ...

  6. SQL Server 2005,2008 正则表达式 替换函数应用详解

    CREATE function dbo.regexReplace ( @source ntext, --原字符串 ), --正则表达式 ), --替换值 , --是否是全局替换 --是否忽略大小写 ) ...

  7. SQL Server 自定义聚合函数

    说明:本文依据网络转载整理而成,因为时间关系,其中原理暂时并未深入研究,只是整理备份留个记录而已. 目标:在SQL Server中自定义聚合函数,在Group BY语句中 ,不是单纯的SUM和MAX等 ...

  8. SQL Server 2005 MD5函数

    原文:SQL Server 2005 MD5函数 在SQL Server 2005下自带的函数HashBytes() ,此函数是微软在SQL Server 2005中提供的,可以用来计算一个字符串的M ...

  9. [翻译]初识SQL Server 2005 Reporting Services Part 2

    原文:[翻译]初识SQL Server 2005 Reporting Services Part 2 在Part 1文章中我们对SQL Server Reporting Services 2005(S ...

随机推荐

  1. extjs form textfield的隐藏方法

    只需将textfield的hidden和hideLabel配置为true就可以了.只设置hidden:true时会显示出来一个:的标签.     this.formpanel = new Ext.Fo ...

  2. 利用DC/DC开关调节器延长DSP系统的电池寿命 - 动态电压调节

    http://www.analog.com/zh/content/dc-to-dc_switching_regulator_insights/fca.html 作者:Sridhar Gurram,Ol ...

  3. java什么时候声明static方法

    1.经常用到的方法,可以声明为static,这样省去了每次new对象的内存空间,因为非static方法,需要new对象才能调用此方法.但因此也产生多线程访问线程安全问题 比如: 2.当一个方法或者变量 ...

  4. 飞天KEY

    RoyCShell.exe -PE -if:"G:\EncryptTool\Finder.exe" -of:"G:\EncryptTool\Finder_enc.exe& ...

  5. OpenCV使用FLANN进行特征点匹配

    使用FLANN进行特征点匹配 目标 在本教程中我们将涉及以下内容: 使用 FlannBasedMatcher 接口以及函数 FLANN 实现快速高效匹配( 快速最近邻逼近搜索函数库(Fast Appr ...

  6. 对于Ian的访谈,不少关于GAN的内容

    文章链接如下: http://3g.163.com/dy/article/DD1GBSLF0511ABV6.html 里面提到胶囊网络,我找了这篇文章看了下: https://blog.csdn.ne ...

  7. 清除linux系统的多余引导

    由于我把系统给升级(update)了,在grub引导模式出现新旧版本(Grub与Grub2)的引导系统分别为正常启动和进入恢复模式各2个引导项,如下图显示:百度找不到相关或类似的教程,只好半夜起来研究 ...

  8. 关于使用jquery时,ie8下提示对象不支持的属性或方法的解决办法

    转自:http://wapapp.baidu.com/auoong/item/538790fcbe87c834d7ff8cde 首先这个问题的前提是已经排除了常见的这个问题.下面说一种今天我碰到的一种 ...

  9. ASP服务器I I S出现authentication mode=Windows错误解决办法

    网上下载的asp.net源码出现 <authentication mode="Windows"/>错误信息 属性 说明 mode 必选的属性. 指定应用程序的默认身份验 ...

  10. Service 生命周期

    有了 Service 类我们如何启动他呢,有两种方法: • Context.startService() • Context.bindService()  1.  在同一个应用任何地方调用 start ...