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 に答える