Listing 1: C# Code for StringConcat Function using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.Text; using System.IO; using System.Runtime.InteropServices; [Serializable] [SqlUserDefinedAggregate( Format.UserDefined, // user-defined serialization IsInvariantToDuplicates = false, // duplicates matter IsInvariantToNulls = true, // don't care about NULLs IsInvariantToOrder = false, // order matters (ignored) IsNullIfEmpty = false, // don't yield NULL if empty set MaxByteSize = 8000)] // maximum size in bytes public struct StringConcat : IBinarySerialize { private StringBuilder sb; public void Init() { this.sb = new StringBuilder(); } public void Accumulate(SqlString s) { if (s.IsNull) { return; // skip NULLs } else { this.sb.Append(s.Value); } } public void Merge(StringConcat Group) { this.sb.Append(Group.sb); } public SqlString Terminate() { return new SqlString(this.sb.ToString()); } public void Read(BinaryReader r) { sb = new StringBuilder(r.ReadString()); } public void Write(BinaryWriter w) { if (this.sb.Length > 4000) // limit sb to 8000 bytes w.Write(this.sb.ToString().Substring(0, 4000)); else w.Write(this.sb.ToString()); } } // end StringConcat