Question

I'm hoping to be able to allow optional parameters to be specified, so I can overload the Accumulate() method, can it be done?

I'd like to overload to allow a delimiter to specified, I've seen others where it must force a delimiter to be specified but this behaviour doesn't suit.

CREATE AGGREGATE dbo.Concatenate (@input nvarchar(max), <OPTIONAL PARAMETER HERE>)
RETURNS nvarchar(max)

For reference, here is the aggregate class code that contains the Accumulate() method I'm looking to overload:

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


namespace CLR.Utilities {
    /// <summary>
    /// <list type="references">
    ///     <reference>
    ///         <name>How to: Create and Run a CLR SQL Server Aggregate</name>
    ///         <link>http://msdn.microsoft.com/en-us/library/91e6taax(v=vs.90).aspx</link>
    ///     </reference>
    ///     <reference>
    ///         <name>SqlUserDefinedAggregateAttribute</name>
    ///         <link>http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.server.sqluserdefinedaggregateattribute(v=vs.90).aspx</link>
    ///     </reference>
    ///     <reference>
    ///         <name>Invoking CLR User-Defined Aggregate Functions (Provides seed code for this function)</name>
    ///         <link>http://technet.microsoft.com/en-us/library/ms131056.aspx</link>
    ///     </reference>
    /// </list>
    /// </summary>
    [Serializable]
    [SqlUserDefinedAggregate(
        Format.UserDefined,                 //use clr serialization to serialize the intermediate result
        IsInvariantToNulls = true,          //optimizer property
        IsInvariantToDuplicates = false,    //optimizer property
        IsInvariantToOrder = false,         //optimizer property
        MaxByteSize = -1)                   //no maximum size in bytes of persisted value
    ]
    public class Concatenate : IBinarySerialize {
        /// <summary>
        /// The variable that holds the intermediate result of the concatenation
        /// </summary>
        private StringBuilder intermediateResult;

        /// <summary>
        /// Initialize the internal data structures
        /// </summary>
        public void Init() {
            this.intermediateResult = new StringBuilder();
        }

        /// <summary>
        /// Accumulate the next value, not if the value is null
        /// </summary>
        /// <param name="value"></param>
        public void Accumulate([SqlFacet(MaxSize = -1)] SqlString value) {
            if (value.IsNull) {
                return;
            }

            this.intermediateResult.Append(value.Value.Trim()).Append(',');
        }

        /// <summary>
        /// Merge the partially computed aggregate with this aggregate.
        /// </summary>
        /// <param name="other"></param>
        public void Merge(Concatenate other) {
            this.intermediateResult.Append(other.intermediateResult);
        }

        /// <summary>
        /// Called at the end of aggregation, to return the results of the aggregation.
        /// </summary>
        /// <returns></returns>
        [return: SqlFacet(MaxSize = -1)]
        public SqlString Terminate() {
            string output = string.Empty;
            //delete the trailing comma, if any
            if (this.intermediateResult != null
                && this.intermediateResult.Length > 0) {
                output = this.intermediateResult.ToString(0, this.intermediateResult.Length - 1).Trim();
            }

            return new SqlString(output);
        }

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

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

And here is the code for deployment that I'd like to modify also if optional parameters can be set:

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Concatenate]') AND type = N'AF')
DROP AGGREGATE [dbo].[Concatenate]
GO

IF  EXISTS (SELECT * FROM sys.assemblies asms WHERE asms.name = N'CLR.Utilities' and is_user_defined = 1)
DROP ASSEMBLY [CLR.Utilities]
GO

ALTER DATABASE [DatabaseName] SET TRUSTWORTHY ON
GO

CREATE ASSEMBLY [CLR.Utilities] FROM 'C:\Path\To\File\CLR.Utilities.dll' WITH PERMISSION_SET = UNSAFE
GO

CREATE AGGREGATE [dbo].[Concatenate] (@input nvarchar(max)) RETURNS nvarchar(max)
EXTERNAL NAME [CLR.Utilities].[CLR.Utilities.Concatenate]
GO

GRANT EXECUTE ON [dbo].[Concatenate] TO PUBLIC
GO
Was it helpful?

Solution 2

As far as I know, there's no way to make clr function or aggregate with optional parameters and that's sad.

OTHER TIPS

You could, however, make the parameter mandatory but optionally null. And, in your C# code test whether the value is null and act accordingly. Something like:

public void Accumulate([SqlFacet(MaxSize = -1)] SqlString value, SqlString delimiter) {
        string _delimiter;
        if (value.IsNull) {
            return;
        }

        if (delimiter.IsNull) {
            _delimiter = string.Empty;
        }
        else {
            _delimiter = Delimiter.Value;
        }

        this.intermediateResult.Append(value.Value.Trim()).Append(_delimiter);
    }

There is a way, though it isn't nice. You simple add the delimiter to the end of the column you're concatenating with a char(0) between them. then in the clr, you can look for char(0) and grab the delimiter to use.

-- concat columns delimited by a comma 
select grp,dbo.clrConcat(surname) as names
  from people

-- concat column delimited by specified character
select grp,dbo.clrConcat(surname + char(0) + '|') as names
  from people

Then in the clr code

''' <summary>  
''' Initialize the internal data structures  
''' </summary>  
Public Sub Init()
    Me.intermediateResult = New StringBuilder()
    delimiter = ","
End Sub

''' <summary>  
''' Accumulate the next value, not if the value is null  
''' </summary>  
''' <param name="value"></param>  
Public Sub Accumulate(ByVal value As SqlString)
    Dim Str As String
    Dim Pos As Integer

    If value.IsNull Then Return

    Pos = value.Value.IndexOf(Chr(0))
    If Pos >= 0 Then
        Str = value.Value.Substring(0, Pos)
        If Pos + 1 < value.Value.Length Then
            delimiter = value.Value.Substring(Pos + 1, 1)
        End If
    Else
        Str = value.Value
    End If

    Me.intermediateResult.Append(Str).Append(delimiter)
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top