Search code examples
c#sql-server.net-assemblyuser-defined-aggregate

Wrong result of user defined aggregate in SQL Server


I have been trying to create custom aggregate function in SQL Server. I finally got it working (wrote assembly in C#).

The goal is to concatenate all strings within a group, but the result is empty string.

Here is my class in C#:

[SqlUserDefinedAggregate(Format.UserDefined, MaxByteSize = 32)]
public struct STRING_CONCAT : IBinarySerialize
{
    //result - concatenated string
    SqlString result;

    public void Init()
    {
        //empty the result
        result = "";
    }

    public void Accumulate(SqlString value)
    {
        result += value;
    }

    public void Merge(STRING_CONCAT value)
    {
        Accumulate(value.Terminate());
    }

    public SqlString Terminate()
    {
        return result;
    }

    public void Read(BinaryReader r)
    {
        r.BaseStream.Position = 0;
        result = r.ReadString();
    }

    public void Write(BinaryWriter w)
    {
        w.Write(result.GetUnicodeBytes());
        w.BaseStream.Position = 0;
    }
}

And here is T-SQL part:

CREATE ASSEMBLY [SQLAggregate]
FROM 'C:\CSharp\SQLAggregate\SQLAggregate\bin\Debug\SQLAggregate.dll'
GO

create aggregate STRING_CONCAT
(@string nvarchar(100))
returns nvarchar(4000)
external name [SQLAggregate].[SQLAggregate.STRING_CONCAT] 

Solution

  • Remove the setting of position on BinaryReader/BinaryWriter and change w.Write(result.GetUnicodeBytes()); to w.Write(result.Value);.