SQL Server中的聚合,常用的比如max,count之类。 我们现在也可以在SQLCLR里创建自定义的聚合。Visual Studio 2005中提供的聚合模板是一个结构,标注了[Serializable],[SqlUserDefinedAggregate]标签,这将让SQLCLR知道这是一个聚合函数。
看一段代码,这段代码来自SQL Server 2005联机丛书,本来自己想写一段,但突然公司有些事要做,没时间了。示例代码作用是合并同一部书(ID相同)的作者。
SQLCLR(五)聚合using System;
SQLCLR(五)聚合
using System.Data;
SQLCLR(五)聚合
using Microsoft.SqlServer.Server;
SQLCLR(五)聚合
using System.Data.SqlTypes;
SQLCLR(五)聚合
using System.IO;
SQLCLR(五)聚合
using System.Text;
SQLCLR(五)聚合
SQLCLR(五)聚合[Serializable]
SQLCLR(五)聚合[SqlUserDefinedAggregate(
SQLCLR(五)聚合    Format.UserDefined, 
//use clr serialization to serialize the intermediate result
SQLCLR(五)聚合
    IsInvariantToNulls = true//optimizer property
SQLCLR(五)聚合
    IsInvariantToDuplicates = false//optimizer property
SQLCLR(五)聚合
    IsInvariantToOrder = false//optimizer property
SQLCLR(五)聚合
    MaxByteSize = 8000//maximum size in bytes of persisted value
SQLCLR(五)聚合
]
SQLCLR(五)聚合
public class Concatenate : IBinarySerialize
}
这里有几个比较重要的方法:Terminate,这个方法是聚合最后调用的方法,它返回最后的值。可以是SQL Server的任何标量。;Accumulate,聚合每处理一行数据的时候都会调用一次,并将要处理的数据传给方法。可以在函数内部进行比如比较,合并之类的处理。;
SQLCLR(五)聚合CREATE TABLE BookAuthors
SQLCLR(五)聚合(
SQLCLR(五)聚合   BookID   
int       NOT NULL,
SQLCLR(五)聚合   AuthorName    
nvarchar(200NOT NULL
SQLCLR(五)聚合)
SQLCLR(五)聚合
SQLCLR(五)聚合
INSERT BookAuthors VALUES(1'Johnson')
SQLCLR(五)聚合
INSERT BookAuthors VALUES(2'Taylor')
SQLCLR(五)聚合
INSERT BookAuthors VALUES(3'Steven')
SQLCLR(五)聚合
INSERT BookAuthors VALUES(2'Mayler')
SQLCLR(五)聚合
INSERT BookAuthors VALUES(3'Roberts')
SQLCLR(五)聚合
INSERT BookAuthors VALUES(3'Michaels')
SQLCLR(五)聚合

SQLCLR(五)聚合SELECT BookID, dbo.MyAgg(AuthorName)
SQLCLR(五)聚合
FROM BookAuthors
SQLCLR(五)聚合
GROUP BY BookID
SQLCLR(五)聚合
结果如下
BookID Author Names

1

Johnson

2

Taylor, Mayler

3

Roberts, Michaels, Steven


Microsoft SQL Server Management Studio为我们提供了数据库内对象的集中管理功能,前面几篇创建的SQLCLR对象,都可以在数据库的可编程性下相应模块里找到。
SQLCLR(五)聚合
这一系列到此就算是结束了,谢谢大家。

相关文章:

  • 2022-12-23
  • 2021-12-20
  • 2022-12-23
  • 2021-10-05
  • 2021-09-28
  • 2021-12-13
猜你喜欢
  • 2021-08-17
  • 2021-06-21
  • 2022-12-23
  • 2021-06-18
  • 2022-12-23
  • 2021-11-10
相关资源
相似解决方案