Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 CLR Custom Aggregate

Author  Topic 

jdblack
Starting Member

11 Posts

Posted - 2011-01-14 : 11:29:42
I'm creating a custom aggregate (eventually a mode). I kept getting an error, so I pared the C# down to a bare minimum. The error comes up when I try to use the aggregate. The only object I'm referencing in Terminate is items, so I guess it must be that, but I don't understand why. I'm initializing it in Init; even if it were empty I thought that should be enough for the items.count to be 0.

quote:
Msg 6522, Level 16, State 2, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "PercBytes":
System.NullReferenceException: Object reference not set to an instance of an object.
System.NullReferenceException:
at PercBytes.Terminate()


Here's the C# code.


[Serializable]

[SqlUserDefinedAggregate(

Format.UserDefined, //use custom serialization to serialize the intermediate result
IsInvariantToNulls = true, //optimizer property
IsInvariantToDuplicates = false, //optimizer property
IsInvariantToOrder = false, //optimizer property
MaxByteSize = 8000) //maximum size in bytes of persisted value

]

public class PercBytes : IBinarySerialize
{
private StringBuilder intermediateResult;
private ArrayList items;

public void Init()
{
this.intermediateResult = new StringBuilder();
this.items = new ArrayList();
}

public void Accumulate(SqlString value)
{
if (value.IsNull)
{
this.items.Add("null");
}
else
{
this.items.Add(value);
}
}

public void Merge(PercBytes other)
{
this.items.Add(other.items);
}

public int Terminate()
{
return items.Count;
}

public void Read(BinaryReader reader)
{
intermediateResult = new StringBuilder(reader.ReadString());
}

public void Write(BinaryWriter writer)
{
writer.Write(this.intermediateResult.ToString());
}
}


Here's the SQL part

CREATE ASSEMBLY CLRLib FROM 'G:\CLRLib.dll'

GO

create AGGREGATE PercBytes (@input nvarchar(max)) RETURNS int

EXTERNAL NAME clrlib.PercBytes

GO

select dbo.PercBytes(BytesSent),App_ID from dbo.fact_runid_1(nolock)
and BytesSent != 0
group by App_ID

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2011-01-14 : 14:08:21
I think you need a constructor in place of your Init function. When the class is instantiated Items is going to not be initialized.
Go to Top of Page
   

- Advertisement -