我有这个 SQL Server 用户定义的聚合:
[SqlUserDefinedAggregate(Format.UserDefined, Name="median", IsInvariantToDuplicates=false, IsInvariantToNulls=true, IsInvariantToOrder=true, IsNullIfEmpty=true, MaxByteSize=8000)]
public class MedianCalculator : IBinarySerialize {
private List<double> values;
public void Init() {
values = new List<double>();
}
public void Accumulate(SqlDouble value) {
if (!value.IsNull)
values.Add(value.Value);
}
public void Merge(MedianCalculator other) {
values.AddRange(other.values);
}
public SqlDouble Terminate() {
if (values == null || values.Count == 0)
return SqlDouble.Null;
values.Sort();
return (values[(int)Math.Floor((values.Count - 1) / 2.0)] + values[(int)Math.Ceiling((values.Count - 1) / 2.0)]) / 2.0;
}
public void Read(BinaryReader r) {
int c = r.ReadInt32();
values = new List<double>(c);
for (int i = 0; i < c; i++)
values.Add(r.ReadDouble());
}
public void Write(BinaryWriter w) {
w.Write(values.Count);
for (int i = 0; i < values.Count; i++)
w.Write(values[i]);
}
}
部署此聚合后,我尝试运行此查询:
select dbo.median(x) from (select 1 as x where 1 = 0) t
我得到这个错误:
A severe error occurred on the current command. The results, if any, should be discarded.
但是,这有效:
create table #t(x int)
select dbo.median(x) from #t
drop table #t
并按预期返回 NULL。
这似乎是 SQL Server 中的一个错误,但我该如何解决呢?
select @@version
Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86) Nov 24 2008 13:01:59 Copyright (c) 1988-2005 Microsoft Corporation Developer Edition on Windows NT 6.1 (Build 7100: )