不多说了,说明后面是完整的代码,用来将字符串型的字段的各行的值拼成一个大字符串,也就是通常所说的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加密存储过程,函数

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

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

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

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

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

  5. Sql server的Merge语句,源表中如果有重复数据会导致执行报错

    用过sql server的Merge语句的开发人员都应该很清楚Merge用来做表数据的插入/更新是非常方便的,但是其中有一个问题值得关注,那就是Merge语句中的源表中不能出现重复的数据,我们举例来说 ...

  6. SQL Server查询某个字段存在哪些表中

    一.查询SQL Server中所有的表 SQL语句:SELECT * FROM sys.tables name列表示所有的表名. 二.查询SQL Server中所有的列 SQL语句:SELECT * ...

  7. SQL SERVER增加、删除、更改表中的字段名 (详询请加qq:2085920154)

    1. 向表中添加新的字段 alter  table  table_name  add  column_name  varchar2(20) not null 2. 删除表中的一个字段 delete t ...

  8. 【SQL Server】利用游标将学生表中的成绩转化为绩点

    软件工程综合实践第一次作业 代码来源:班上同学的数据库大作业 alter table sc add GPA float; --加入绩点列 alter table sc ,);--将表按原始位置顺序编号 ...

  9. SQL Server从读写频繁的大表中删除大批量数据

    如果我们直接用delete from语句来删除读写频繁的大表中的数据,很有可能会因为where的条件是全表扫描从而导致整个表被锁住了.如果该表是读写频繁的生产库那简直就是一场灾难,所有的线上读写请求都 ...

随机推荐

  1. design-twitter

    https://leetcode.com/problems/design-twitter/ class Twitter { unordered_map<int, set<int> & ...

  2. go语言基础之append函数的使用

    1.append函数的使用 作用:在原切片的末尾添加元素 示例: package main //必须有个main包 import "fmt" func main() { s1 := ...

  3. jQuery实现新浪微博自动底部加载的方法

    jQuery ScrollPagination plugin 是一个jQuery 实现的支持无限滚动加载数据的插件. 地址:http://andersonferminiano.com/jquerysc ...

  4. RUP---统一软件开发过程

    更详细的见:http://www.ibm.com/developerworks/cn/rational/r-rupbp/ 本文引用:http://baike.baidu.com/view/223583 ...

  5. RS开发值提示默认为当前月

    在报表的开发过程中,按月查询数据,但是由于数据仓库中涉及多年历史数据,而用户最关心的却是最近的数据,针对这个情况.当用户第一次点击报表想看到的就是当前月的数据,那么如何去做呢? 下面用一个小例子来实战 ...

  6. (转)深入浅出K-Means算法

    原文地址:http://www.csdn.net/article/2012-07-03/2807073-k-means 摘要:在数据挖掘中,K-Means算法是一种 cluster analysis ...

  7. Struts2远程代码执行漏洞预警

    近期struts2 框架再现高危远程命令执行漏洞,漏洞编号S2-045,CVE编号CVE-2017-5638.利用此漏洞可对使用了struts2框架的网站进行远程命令执行,对服务器造成威胁.请相关单位 ...

  8. PHP高级教程-Error

    PHP 错误处理 在 PHP 中,默认的错误处理很简单.一条错误消息会被发送到浏览器,这条消息带有文件名.行号以及描述错误的消息. PHP 错误处理 在创建脚本和 Web 应用程序时,错误处理是一个重 ...

  9. cmd命令之set详解

    C:\Users\Administrator>set ALLUSERSPROFILE=C:\ProgramData APPDATA=C:\Users\Administrator\AppData\ ...

  10. Java从零开始学二十一(集合List接口)

    一.List接口 List是Collection的子接口,里面可以保存各个重复的内容,此接口的定义如下: public interface List<E> extends Collecti ...