SQL 服务器中用户定义聚合的错误结果

Wrong result of user defined aggregate in SQL Server

我一直在尝试在 SQL 服务器中创建自定义聚合函数。我终于让它工作了(用 C# 编写了程序集)。

目标是连接一个组内的所有字符串,但结果是空字符串。

这是我在 C# 中的 class:

[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;
    }
}

这里是 T-SQL 部分:

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] 

去掉BinaryReader/BinaryWriter上position的设置,把w.Write(result.GetUnicodeBytes());改成w.Write(result.Value);