为SQL Server创建自定义“ First_Value”聚合

时间:2018-12-22 11:53:39

标签: c# sql-server clr aggregation

我已经在Visual Studio(CLR)中为SQL Server创建了新的自定义聚合。 SQL Server在每次迭代中都运行“累积”功能,我们不希望这样做。我们只想对每个组的第一行运行一次Accumulate。我该怎么办?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.IO;
using System.Runtime.InteropServices;

[Serializable]
[SqlUserDefinedAggregate(Format.Native,
                         IsInvariantToDuplicates = false,
                         IsInvariantToNulls = true,
                         IsInvariantToOrder = true,
                         IsNullIfEmpty = true,
                         Name = "MyStruct")]
public struct MyStruct
{
    float myResult;

    public void Init()
    {
        myResult = 0;
    }

    public void Accumulate(SqlDouble myValue)
    {    
        if (!myValue.IsNull)
        {
            myResult = (float)myValue;
        }
    }

    public void Merge(MyStruct group)
    {
         myResult = group.myResult;
    }

    public SqlDouble Terminate()
    {
         if (myResult != 0)
         {
              return new SqlDouble(myResult);
         }
         else
         {
              return SqlDouble.Null;
         }
    }
}

0 个答案:

没有答案