我在SQL中编写了这个函数
alter function TVprest (@emitente int, @mes int, @ano int)
returns float
as
begin
declare @tcu float;
select @tcu = sum(cast(vtprest as money))
from ctrc
where emitente = @emitente and MONTH (EMISSAODATA ) = @mes
and YEAR (EMISSAODATA)=@ano and status = 'A'
if (@tcu is null)
set @tcu = 0;
return @tcu
end
尝试使用以下代码在C#中调用相同的函数:
public double TVprest (int emitente, int mess, int anno)
{
double saida;
SqlConnection abre1 = Tconex.GetConnection();
SqlDataAdapter da3 = new SqlDataAdapter();
if (abre1.State == ConnectionState.Closed) { abre1.Open(); }
SqlParameter emit = new SqlParameter("@emitente", SqlDbType.Int);
emit.Value = emitente;
SqlParameter mes = new SqlParameter("@mes", SqlDbType.Int);
mes.Value = mess;
SqlParameter ano = new SqlParameter("@ano", SqlDbType.Int);
ano.Value = ano;
SqlCommand TotalF = new SqlCommand("SELECT dbo.Tcupom(@emitente,@mes,@ano),", abre1);
TotalF.CommandType = CommandType.Text;
saida = Convert.ToDouble(TotalF.ExecuteScalar());
return saida;
}
运行时出现此错误:
无法将参数值从SqlParameter转换为Int32
有什么问题?使用以下参数调用函数:
double Tvprest = impx.TVprest(504, 5, 2013);
lblVtprest.Text = Tvprest.ToString();
答案 0 :(得分:4)
您尚未将参数添加到命令
SqlCommand TotalF = new SqlCommand("SELECT dbo.Tcupom(@emitente,@mes,@ano),", abre1);
TotalF.Parameters.Add(emit);
TotalF.Parameters.Add(mes);
TotalF.Parameters.Add(ano);
saida = Convert.ToDouble(TotalF.ExecuteScalar());
但是,我认为你缺少在你的问题中解释一些事情。你有一个名为TVprest的功能,但你打电话给SELECT dbo.Tcupom
。不清楚Tcupom
答案 1 :(得分:1)
正如史蒂夫正确指出的那样,这里的根本错误是没有正确添加参数。但是,作为一般的代码错误避免技巧,您可能希望尝试像dapper这样的工具,这样可以更加难以理解它。例如:
return abre1.Query<double>("SELECT dbo.Tcupom(@emitente,@mess,@anno)",
new { emitente, mess, anno }).Single();
这里有所有,但它正确,并且易于阅读。它甚至适用于更复杂的类型,即
string region = ...
var customers = connection.Query<Customer>(
"select * from Customers where Region = @region",
new { region }).ToList();