C# 从CLR内的SQL函数获取字符串值
尝试的非工作解决方案包括在下面。 我有一个名为get_parameter的sql函数,它在表中查找给定字符串并返回关联字符串:C# 从CLR内的SQL函数获取字符串值,c#,.net,sql-server,tsql,sqlclr,C#,.net,Sql Server,Tsql,Sqlclr,尝试的非工作解决方案包括在下面。 我有一个名为get_parameter的sql函数,它在表中查找给定字符串并返回关联字符串: declare @str varchar(20); set @str = dbo.get_parameter('filecount') print @str 它起作用了!我运行这个程序,它精确地打印出它应该打印的内容。在本例中,参数是字符串“44” 现在我想运行一个C CLR。但是我希望CLR能够查找它需要的参数 [SqlFunction(DataAccess
declare @str varchar(20);
set @str = dbo.get_parameter('filecount')
print @str
它起作用了!我运行这个程序,它精确地打印出它应该打印的内容。在本例中,参数是字符串“44”
现在我想运行一个C CLR。但是我希望CLR能够查找它需要的参数
[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;
}
}
然而,这是行不通的。当它从get_参数返回时,它总是认为cnt的值为null或空
根据请求,get_参数的代码
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
我已经尝试了下面Mike Dinescu的解决方案,但问题是对ExecuteScalar的调用仍然返回空值。我确实尝试更改为CommandType.Text,在这种情况下,我得到了以下有趣的消息:
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.
这很有趣,因为我正在查看它在何处添加参数@SelectedParameterName
command.Parameters.Add(new SqlParameter("@SelectedParameterName", SqlDbType.NVarChar )).Value = "filecount";
如果要执行.NET中的用户定义函数或存储过程,应将CommandType设置为CommandType.StoredProcedure,并在执行命令之前向命令对象添加所需的参数
command.CommandType = CommandType.StoredProcedure;
command.CommandText = @"dbo.get_parameter";
// here you add the paramters needed for your procedure/function
// in your case it will be just one (make sure you add the correct name for you function)
command.Parameters.Add(new SqlParamter("SelectedParameterName", SqlDbType.NVarChar));
command.Prepare();
command.Parameters[0].Value = "filecount";
string cnt = (string)command.ExecuteScalar();
你是在比较苹果和桔子吗?SQL函数的执行方式与手动脚本不完全相同。EXEC get_参数'filecount'与SET…=dbo.get_参数'filecount'不同。您说这是一个函数,但在CLR中调用时就像一个过程。更改CLR代码以选择dbo.get_参数'filecount'显示dbo.get_参数的定义。至少是头球,如果不是整个身体的话。我试过这个。不工作。无法识别CommandType.StoredProcess,即使我使用System.Data.SqlClient,也无法识别新的SqlCommandParameterVM。使用System.Data添加修复了这两个问题。有趣的是,当我设置CommandType.Text并将CommandText设置为@select parametervalue from IF103_Parameters,其中ParameterName='dsams_filecount'。。。注意,当我使用直接选择而不是存储过程调用时,它是有效的。