0

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] 
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. – Tab Alleman Dec 26 '17 at 14:25
  • 2
    @TabAlleman this question includes all this. – Evk Dec 26 '17 at 14:32
  • @Evk where does it show the input and expected output? – Tab Alleman Dec 26 '17 at 14:34
  • 1
    @TabAlleman expected output - concatenated strings. Actual output - empty string. – Evk Dec 26 '17 at 14:44

1 Answers1

0

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

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
TcKs
  • 25,849
  • 11
  • 66
  • 104