带有datetime参数的SQLCLR自定义聚合

时间:2015-10-19 13:14:39

标签: c# sql-server datetime clr

HY,

我几个月前在post上发布了一个关于CLR用户定义聚合的问题。

这适用于int。但现在我想用datetime参数执行相同的功能。

但我无法上班。 像这样,代码将无法正常工作......问题在于在sql server上生成此错误的读取函数:

System.ArgumentOutOfRangeException: Les graduations doivent être comprises entre DateTime.MinValue.Ticks et DateTime.MaxValue.Ticks.
Nom du paramètre : ticks
System.ArgumentOutOfRangeException: 
   à System.DateTime..ctor(Int64 ticks)
   à sMaxDatetime.Read(BinaryReader reader)

所以我尝试将我的sql Datetime转换为带有this的刻度,但它没有正常工作。我在转换为datetime时遇到了OverflowException。

我找到了这个post,看来我无法将我的日期时间映射到BinaryReader ......

所以我没有想法来做我的聚合......

你有想法这样做吗?

以下是实际代码:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Diagnostics.Eventing.Reader;
using System.Globalization;
using Microsoft.SqlServer.Server;
using System.Text;
using System.Collections;
using System.IO;

[Serializable]
[SqlUserDefinedAggregate(
    Format.UserDefined,
    IsInvariantToOrder = true,
    IsInvariantToNulls = true,
    IsInvariantToDuplicates = true,
    MaxByteSize = -1)]
public struct sMaxDatetime : IBinarySerialize
{
    #region Helpers

    private struct MyData
    {
        public string Data { get; set; }
        public DateTime? Group { get; set; }

        public int CompareTo(MyData other)
        {
            if (Group == null)
                return other.Group == null ? 0 : -1;

            if (other.Group == null)
                return 1;

            return Group.Value.CompareTo(other.Group.Value);
        }

        public static bool operator < (MyData left, MyData right)
        {
            return left.CompareTo(right) == -1;
        }

        public static bool operator > (MyData left, MyData right)
        {
            return left.CompareTo(right) == 1;
        }
    }

    #endregion

    private MyData _maxItem;

    public void Init()
    {
        _maxItem = default(MyData);
    }

    public void Accumulate(SqlString data, SqlDateTime group)
    {
        if (!data.IsNull && !group.IsNull)
        {
            var current = new MyData
            {
                Data = data.Value,
                Group = group.Value,
            };

            if (current > _maxItem)
            {
                _maxItem = current;
            }
        }
    }

    public void Merge(sMaxDatetime other)
    {
        if (other._maxItem > _maxItem)
        {
            _maxItem = other._maxItem;
        }
    }

    public SqlString Terminate()
    {
        return _maxItem.Data;
    }

    public void Read(BinaryReader reader)
    {
        //if (reader.ReadBoolean())
        //{
            _maxItem.Data = reader.ReadString();
            _maxItem.Group = new DateTime(reader.ReadInt64());
        //}
        //else
        //{
        //    _maxItem = default(MyData);
        //}
    }

    public void Write(BinaryWriter writer)
    {
        if (_maxItem.Group.HasValue)
        {
            writer.Write(true);
            writer.Write(_maxItem.Group.Value.ToString());
            writer.Write(_maxItem.Data);
        }
        else
        {
            writer.Write(false);
        }
    }
}

PS:我有这个相关的post sql_variant unclosed谁可以做技巧但我无法开始工作。

1 个答案:

答案 0 :(得分:0)

我认为你在使用自定义结构进行过于努力来保存日期时间和名称。这就是我想出的:

using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;

[Serializable]
[SqlUserDefinedAggregate(Format.UserDefined, Name = "sMaxDatetime", MaxByteSize = -1)] 
public struct SO33215409 : IBinarySerialize
{
    private SqlString _data;
    private SqlDateTime _latest;
    public void Init()
    {
        _data = SqlString.Null;
        _latest = SqlDateTime.MinValue;
    }

    public void Accumulate(SqlString data, SqlDateTime dt)
    {
        if (dt > _latest)
        {
            _data = data;
            _latest = dt;
        }
    }

    public void Merge (SO33215409 Group)
    {
        if (Group._latest > _latest)
        {
            _data = Group._data;
            _latest = Group._latest;
        }
    }

    public SqlString Terminate ()
    {
        return _data;
    }

    public void Write (BinaryWriter w)
    {
        w.Write(_data.IsNull);
        w.Write(_latest.IsNull);
        if (_data.IsNull == false)
        {
            w.Write(_data.Value);
        }
        if (_latest.IsNull == false)
        {
            w.Write(_latest.Value.Ticks);
        }
    }
    public void Read(BinaryReader r)
    {
        bool dataIsNull = r.ReadBoolean();
        bool latestIsNull = r.ReadBoolean();
        if (dataIsNull)
        {
            _data = SqlString.Null;
        }
        else
        {
            _data = r.ReadString();
        }
        if (latestIsNull)
        {
            _latest = SqlDateTime.Null;
        }
        else
        {
            DateTime d = new DateTime(r.ReadInt64());
            _latest = new SqlDateTime( d );
        }
    }
}

运行它的SQL:

WITH cte AS (
    SELECT * FROM (VALUES
    ('Manager'    , 'emp 1'    ,   dateadd(year, -35, getdate())),    
    ('Manager'    , 'emp 2'    ,   dateadd(year, -42, getdate())),    
    ('Developer'  , 'emp 3'    ,   dateadd(year, -36, getdate())),    
    ('Developer'  , 'emp 4'    ,   dateadd(year, -45, getdate())),    
    ('Developer'  , 'emp 5'    ,   dateadd(year, -22, getdate())) 
    ) AS x([Type], [Name], [DOB])
)
SELECT [Type], dbo.[sMaxDatetime]([Name], [DOB])
FROM cte
GROUP BY [Type]