Attempted (non-working) solution included below. I have an sql function called get_parameter which looks in a table for a given string and returns the associated string:
declare @str varchar(20);
set @str = dbo.get_parameter('filecount')
print @str
It works! I run this and it prints out exactly what it should print. In this case, the parameter is the string '44'.
Now I want to run a C# CLR. But I want the CLR to be able to look up the parameter that it needs.
[SqlFunction(DataAccess = DataAccessKind.Read)]
public static string Import_TestFunc()
{
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
SqlCommand command = new SqlCommand();
command.Connection = conn;
conn.Open();
// Find out how many files DSAMS processing requires.
command.CommandText = @"EXEC get_parameter 'filecount' ";
string cnt = (string)command.ExecuteScalar();
if (String.IsNullOrEmpty(cnt))
{
return "'cnt' not found."; // error return code. can't find this parameter.
}
return cnt;
}
}
However, this does not work. It constantly thinks the value for cnt is null (or empty) when it returns from get_parameter.
As requested, the code for get_parameter
ALTER FUNCTION [dbo].[get_parameter]
(
@SelectedParameterName nvarchar(max)
)
RETURNS nvarchar(max)
AS
BEGIN
DECLARE @result nvarchar(max);
SET @result = (SELECT ParameterValue from Parameters WHERE ParameterName = @SelectedParameterName);
RETURN isnull(@result,'');
END
I have tried the solution as per Mike Dinescu below, but it problem is that the call to ExecuteScalar() still returns a null. I did try to change to CommandType.Text and in that case I get the following interesting message:
A .NET Framework error occurred during execution of user-defined routine or aggregate "Import_TestFunc":
System.Data.SqlClient.SqlException: Procedure or function 'get_parameter' expects parameter '@SelectedParameterName', which was not supplied.
This is interesting, because I'm looking right at where it adds the parameter @SelectedParameterName.
command.Parameters.Add(new SqlParameter("@SelectedParameterName", SqlDbType.NVarChar )).Value = "filecount";