2

我正在尝试运行一个存储过程,但由于某种原因它一直在告诉我"Specified cast is not valid"。“ hidSelectedExpenseIDs”是一个隐藏字段,填充了一个 id 的 javascript 数组。

示例:"hidSelectedExpenseIDs.Value"看起来像“123,124,125,126”。因此,为什么我.Split(',')在那里。

这是我的代码:

public void hasExhistingExpenseInvoice()
{
    string[] Expenses = hidSelectedExpenseIDs.Value.Split(',');

    //check if there is an existing invoice. Then report back to the user so the
    //user knows if he/she has to check overwrite option.
    bool invoiceExists = false;

    foreach (var expense in Expenses)
    {
        var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
        var command = new SqlCommand("p_CaseFiles_Expenses_InvoiceExhists", connection);
        command.Parameters.Add(new SqlParameter("@ExpenseID", SqlDbType.Int));
        command.Parameters["@ExpenseID"].Value = Convert.ToInt32(expense);
        command.CommandType = CommandType.StoredProcedure;
        try
        {
            connection.Open();
            invoiceExists = (bool)command.ExecuteScalar();
            if (invoiceExists)
            {
                //previous invoice exhists
                Warning1.Visible = true;
                Warning1.Text = "There is an exhisting Invoice.";
            }
        }
        catch (SqlException sql)
        {
            lblStatus.Text = "Couldn't connect to the Database - Error";
            lblStatus.ForeColor = System.Drawing.Color.Red;
        }
        catch (Exception ex)//catches exception here
        {
            lblStatus.Text = "An error occured";
            lblStatus.ForeColor = System.Drawing.Color.Red;
        }
        finally
        {
            if (connection.State == ConnectionState.Open)
                connection.Close();
        }
    }
}

这是我的存储过程:

ALTER PROCEDURE dbo.[InvoiceExhists]
@ExpenseID int
AS
BEGIN
    SELECT InvNumber FROM dbo.Expenses from ExpID = @ExpenseID
END
4

3 回答 3

4

逻辑有问题。

您的查询返回一个数字,并且您尝试将其直接转换为布尔值,这在 C# 中无法完成。

某些语言会将任何非零解释为 true,但 C# 并非如此,它会引发异常。

您将需要比较返回的值。

在这种情况下,您应该只检查是否有值,因为如果发票不存在,将返回 NULL。

这看起来像这样:

invoiceExists = command.ExecuteScalar() != null ;

此外,我建议阅读此线程并考虑使用 UDF 而不是标量存储过程。

于 2012-10-22T15:33:47.703 回答
2

更改您的存储过程。这符合您的要求

ALTER PROCEDURE [dbo].[InvoiceExhists]
@ExpenseID int
AS
BEGIN
if exists(select * Expenses where ExpID = @ExpenseID)
select 1
else
select 0
END
于 2012-10-22T14:46:46.233 回答
0

该异常可能是由于invoiceExists = (bool)command.ExecuteScalar();考虑到它是在 try 语句中发生的唯一转换。您需要查看的返回结果ExecuteScalar()来解决您的问题。

于 2012-10-22T14:33:42.357 回答