我在 SQL Server 中的存储过程中使用函数并返回十进制结果。
在 C# 中,我需要获取它,但出现错误:
"INVALLD CastEXCEPTION was unhandeld by user code" "an exception of type 'system.invaildCastException' occured...'
我的 C# 代码:
decimal? val = null;
SqlConnection con = new SqlConnection(conStr);
con.Open();
using (con)
{
SqlCommand cmd = new SqlCommand("dbo.spSetOrderDetails", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = cmd.Parameters.AddWithValue("@OrderDetailsItemsTVP", dt);
tvpParam.SqlDbType = SqlDbType.Structured;
// this part of code return the SUM
SqlParameter returnParam = cmd.Parameters.Add("@RESULT", SqlDbType.Decimal);
returnParam.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
val = (decimal)cmd.Parameters["@RESULT"].Value;--HERE I GET THE EXCEPTION
}
con.Close();
return (decimal)val;
最佳答案
您不能将带有 ParameterDirection.ReturnValue 的参数转换为非整数的数据类型。
The RETURN statement在 T-SQL 中只能返回整数值。
但是,如果您绝对确定您的存储过程总是以 RETURN xxx 之类的内容结尾,那么您可以
val = Convert.ToDecimal(cmd.Parameters["@RESULT"].Value);
关于c# - 为什么我会收到此错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32933436/