引用http://msdn.microsoft.com/zh-cn/library/ms131056(SQL.90).aspx
In Transact-SQL SELECT statements, you can invoke common language runtime (CLR) user-defined aggregates, subject to all the rules that apply to system aggregate functions.
The following additional rules apply:
- The current user must have EXECUTE permission on the user-defined aggregate.
- User-defined aggregates must be invoked using a two-part name in the form of schema_name.udagg_name.
- The argument type of the user-defined aggregate must match or be implicitly convertible to the input_type of the aggregate, as defined in the CREATE AGGREGATE statement.
- The return type of the user-defined aggregate must match the return_type in the CREATE AGGREGATE statement.
Here is an example of a user-defined aggregate function that concatenates a set of string values taken from a column in a table:
[C#]
[Visual Basic]
Once you compile the code into MyAgg.dll, you can register the aggregate in SQL Server as follows:
CREATE ASSEMBLY MyAgg FROM 'C:/MyAgg.dll' GO CREATE AGGREGATE MyAgg (@input nvarchar(200)) RETURNS nvarchar(max) EXTERNAL NAME MyAgg.Concatenate
注意: On a SQL Server 2005 database with a compatibility level of "80," you cannot create managed user-defined types, stored procedures, functions, aggregates, or triggers. To take advantage of these CLR integration features of SQL Server 2005, you must use the sp_dbcmptlevel (Transact-SQL) stored procedure to set the database compatibility level to "90.".
注意: Managed C++ database objects, such as scalar-valued functions, that have been compiled with the /clr:pure Visual C++ compiler option are not supported for execution in SQL Server 2005 RTM.
As with most aggregates, the bulk of the logic is in the Accumulate method. Here, the string that is passed in as a parameter to the Accumulate method is appended to the StringBuilder object that was initialized in the Init method. Assuming that this is not the first time the Accumulate method has been called, a comma is also appended to the StringBuilder prior to appending the passed-in string. At the conclusion of the computational tasks, the Terminate method is called, which returns the StringBuilder as a string.
For example, consider a table with the following schema:
CREATE TABLE BookAuthors ( BookID int NOT NULL, AuthorName nvarchar(200) NOT NULL )Then insert the following rows:
INSERT BookAuthors VALUES(1, 'Johnson') INSERT BookAuthors VALUES(2, 'Taylor') INSERT BookAuthors VALUES(3, 'Steven') INSERT BookAuthors VALUES(2, 'Mayler') INSERT BookAuthors VALUES(3, 'Roberts') INSERT BookAuthors VALUES(3, 'Michaels')The following query would then produce the following result:
SELECT BookID, dbo.MyAgg(AuthorName) FROM BookAuthors GROUP BY BookID
BookID | Author Names |
---|---|
1 |
Johnson |
2 |
Taylor, Mayler |
3 |
Roberts, Michaels, Steven |