【问题标题】:Wrong result of user defined aggregate in SQL ServerSQL Server 中用户定义聚合的错误结果
【发布时间】:2018-06-07 08:55:35
【问题描述】:

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

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

这是我的 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;
    }
}

这里是 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] 

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。跨度>
  • @TabAlleman 这个问题包括所有这些。
  • @Evk 它在哪里显示输入和预期输出?
  • @TabAlleman 预期输出 - 连接字符串。实际输出 - 空字符串。

标签: c# sql-server .net-assembly user-defined-aggregate


【解决方案1】:

去掉BinaryReader/BinaryWriter上的位置设置,将w.Write(result.GetUnicodeBytes());改为w.Write(result.Value);。

【讨论】:

  • 然后我得到EndOfStreamException
  • 在这种情况下。写入字符串而不是 unicode 字节。 w.Write(result.Value):
猜你喜欢
  • 2010-12-30
  • 1970-01-01
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-21
  • 2021-06-06
  • 2019-07-20
相关资源
最近更新 更多