With regards to this question here SQL CLR return two new columns I am trying to create a simple SQL CLR function, where I can pass two strings into the function and it passes me back two NEW columns.
So say I have the following data:-
Col A Col B
Bob Joe
Jane John
I want to be able to pass Col A and Col B to a CLR function and have it return something like this (whereby Col C and D are new columns):-
Col A Col B Col C Col D
Bob Joe BobCLR JoeCLR
Jane John JaneCLR JohnCLR
I have the following code:-
[SqlFunction(FillRowMethodName = "FillRow")]
public static IEnumerable MyCLRFunction(string A, string B)
{
String[] values = new String[2];
values[0] = A+"CLR";
values[1]= B+"CLR";
return values;
}
private static void FillRow(Object obj, out string C, out string D)
{
String[] row = (object[])obj;
C = (string)row[0];
D = (string)row[1];
}
I can register the assembly in SQL Server ok using CREATE ASSEMBLY
I can create the function ok in SQL Server as follows:-
CREATE FUNCTION dbo.MyCLRFunction(@a [nvarchar](4000), @b [nvarchar](4000))
RETURNS TABLE
(c [nvarchar](4000) null, d [nvarchar](4000) null) with execute as caller
AS
EXTERNAL NAME [MyNamespace].[CLRFunctions].[MyCLRFunction]
However when I do:-
SELECT * FROM MyCLRFunction('Bob','Joe')
Im getting:-
Msg 6260, Level 16, State 1, Line 1
An error occurred while getting new row from user defined Table Valued Function :
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.String[]'.
System.InvalidCastException:
at CLRFunctions.FillRow(Object obj, String& C, String& D)
Ok have managed to do this now using a KeyValuePair within an Ienumerable.