[英]Object cannot be cast from DBNull to other types in stored procedure with output parameter
I want to use a stored procedure using SQL Server in a C# application that returns an output parameter but after trying many different ways I haven't realized how to do this. 我想在返回输出参数的C#应用程序中使用一个使用SQL Server的存储过程,但是在尝试了许多不同的方法之后,我还没有意识到如何做到这一点。
This procedure should return a variable/parameter called "recargo" (surcharge) which value varies depending on the age, gender and marital status of a client. 此过程应返回一个称为“补货”(附加费)的变量/参数,该值根据客户的年龄,性别和婚姻状况而变化。 The procedure also has an input parameter which is the ID of the client 该过程还具有一个输入参数,该参数是客户端的ID
The app returns a DBNull exception which I already tried fixing with code, but it still doesn't return a value. 该应用程序返回一个DBNull异常,我已经尝试使用代码修复该异常,但是它仍然没有返回值。 It's returning a null always. 它总是返回null。
CREATE OR ALTER PROCEDURE CalcularRecargo
@rut NVARCHAR(10),
@recargo DECIMAL OUTPUT
AS
BEGIN
DECLARE @fecha DATETIME,
@sexo TINYINT,
@ecivil TINYINT,
@edad INT
SELECT
@fecha = cl.FechaNacimiento,
@sexo = cl.IdSexo,
@ecivil= cl.IdEstadoCivil
FROM
Contrato c
JOIN
Cliente cl ON c.RutCliente = cl.RutCliente
WHERE
c.RutCliente = @rut
--HERE I CALCULATE THE AGE, I DON'T KNOW IF THIS IS CORRECT
BEGIN
SET @edad = (CONVERT(INT, CONVERT(CHAR(8), GETDATE(), 112)) - CONVERT(CHAR(8), @fecha, 112)) / 10000
END
--if the age is between some of these ranges, the surcharge (@recargo) should be increased.
IF @edad >= 18 AND @edad <=25
BEGIN
SET @recargo = @recargo + 3.6
END
ELSE IF @edad >=26 AND @edad <=45
BEGIN
SET @recargo = @recargo + 2.4
END
ELSE
BEGIN
SET @recargo = @recargo + 6
END
--same with gender.
IF @sexo = 1
BEGIN
SET @recargo = @recargo + 2.4
END
ELSE
BEGIN
SET @recargo = @recargo + 1.2
END
--same with marital status
IF @ecivil = 1
BEGIN
SET @recargo = @recargo + 4.8
END
ELSE IF @ecivil = 2
BEGIN
SET @recargo = @recargo + 2.4
END
ELSE
BEGIN
SET @recargo = @recargo + 3.6
END
RETURN
END;
Here is the C# code of the method: 这是该方法的C#代码:
public static double CalcularRecargo(string rut)
{
double recargo = 0.0;
SqlConnection conexion = new SqlConnection(ConSql.conexion);
try
{
conexion.Open();
SqlCommand cmd = new SqlCommand("CalcularRecargo", conexion);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter ParRut = new SqlParameter("@rut", SqlDbType.VarChar);
ParRut.Value = rut;
cmd.Parameters.Add(ParRut);
SqlParameter ParRecargo = new SqlParameter("@recargo", SqlDbType.Decimal);
//ParRecargo.Direction = ParameterDirection.Output;
cmd.Parameters.Add(ParRecargo).Direction=ParameterDirection.Output;
cmd.ExecuteNonQuery();
// IF I UNCOMMENT AND USE THIS CODE IT STILL RETURNS A NULL.
var prerecargo = cmd.Parameters["@recargo"].Value;
if (prerecargo != DBNull.Value)
@recargo = Convert.ToDouble(prerecargo);
// IF I UNCOMMENT AND USE THE CODE BELOW IT RETURNS THE DBNULL EXCEPTION
// recargo = Convert.ToDouble(cmd.Parameters["@recargo"].Value);
}
catch(Exception error)
{
MessageBox.Show(error.Message);
}
finally
{
conexion.Close();
}
return recargo;
}
And Here is the other part of the C# Code where I implement it: 这是我实现它的C#代码的另一部分:
private void button1_Click(object sender, EventArgs e)
{
double recargo = 0;
double primaanual = 0;
double primamensual = 0;
if (ComboTitular.Text != "")
{
recargo = Contrato.CalcularRecargo(ComboTitular.Text);
}
if (recargo > 0 && ComboPlan.Text != "")
{
primaanual = Plan.planes.Find(i => i.Nombre == ComboPlan.Text).PrimaBase + recargo;
primamensual = primaanual / 12;
LblPrimaAnual.Text = primaanual.ToString();
LblPrimaMensual.Text = primamensual.ToString();
}
else
{
MessageBox.Show("Seleccione un plan por favor");
}
try
{
Contrato con = new Contrato(numcontrato, feccreacion, fectermino, ComboTitular.Text, ComboPlan.Text, poliza, inivig, finvig, estavig, declarasalud, primaanual, primamensual, observacion);
string resultado = con.AgregarContrato(con);
MessageBox.Show(resultado);
}
catch (Exception error)
{
MessageBox.Show("Contract already exists");
}
}
NOTE : I deleted a lot of extra code to make the question clearer 注意 :我删除了很多额外的代码以使问题更清楚
Thanks in advance 提前致谢
I think the issue is that @recargo is NULL because it is never assigned an initial value before the calculations. 我认为问题在于@recargo为NULL,因为在计算之前它从未分配过初始值。
Find below a quick repro and documentation link for more details: 在下面找到快速复制和文档链接以获取更多详细信息:
All arithmetic operators (+, -, *, /, %), bitwise operators (~, &, |), and most functions return null if any of the operands or arguments is null , except for the property IsNull Find more details at https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/handling-null-values 如果任何操作数或参数为null , 则所有算术运算符(+,-,*,/,%),按位运算符(〜,&,|)和大多数函数都将返回null ,除了属性IsNull以外,还请参见https ://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/handling-null-values
DECLARE @recargo DECIMAL
-- @recargo is NULL
SELECT @recargo
SET @recargo = @recargo + 2.4
SELECT @recargo --NULL
SET @recargo = 0 --INITIALIZING THE VARIABLE
SET @recargo = @recargo + 2.4
-- @recargo is 2
SELECT @recargo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.