Variable numbers of parameters in a SqlClr UDF or Stored Proc

extended-stored-proceduresql-clr

Lets say I have the following signature for a CLR Stored Proc or UDF:

[Public]
public static void RaisError(
    string message, 
    short severity, 
    short state, 
    params object[] args)

The generated DDL is

CREATE PROCEDURE [dbo].[RaisError]
    @message [nvarchar](4000), 
    @severity [smallint],
    @state [smallint],
    @args /* Error: Unsupported type. */
AS EXTERNAL NAME [SqlSaturdayClr].[StoredProcedures].[RaisError];

I can manually write DDL to reference the stored procedure with any number of variables, defaulting them all to null. However, is there a T-SQL way to say "this stored procedure has a variable number of arguments" in the same way as sp_executesql does?

From this codeproject article it seems that extended stored procs intrinsically have a varariable number of variables and you have to enforce variable length in the code. Is my only option to use an extended stored procedure?

Best Answer

I can manually write DDL to reference the stored procedure with any number of variables, defaulting them all to null. However, is there a T-SQL way to say "this stored procedure has a variable number of arguments" in the same way as sp_executesql does?

No, there's no built-in way to do this.

Is my only option to use an extended stored procedure?

You should avoid writing an extended stored procedure, since these have been deprecated since SQL Server 2005 and generally cause more problems than they solve. There is no really good way to simulate the optional parameter behaviour of things like sp_executesql with a SQLCLR procedure or function.

Various workarounds can be suitable depending on the situation. The most often recommended is a T-SQL procedure or function wrapper, though I have also seen people experiment with passing a SQLCLR type (containing an array of values, for example) as well. The T-SQL equivalent to that would be a table-valued parameter.