简体   繁体   English

检查数据库表Asp.net C#中的值

[英]Check if value in database table Asp.net C#

I have a stored procedure that would count the number of times a value is in a database. 我有一个存储过程,该过程将计算一个值在数据库中的次数。 However in the code behind for loop when it reaches (int)command.ExecuteScalar(); 但是在到达(int)command.ExecuteScalar(); for循环后面的代码中(int)command.ExecuteScalar(); the loop stops and asks to supply parameter for @invoice2. 循环停止并要求提供@ invoice2的参数。

Stored Procedure: 存储过程:

select count(*) as CountInvoice where invoice1=@invoice1 or @invoice2=@invoice`2

Code Behind: 背后的代码:

using (SqlCommand command = new SqlCommand("sp_Count", conn))
{

    foreach (TextBox textBox in placehldr1.Controls.OfType<TextBox>())
    {

        count += 1;

        command.CommandType = CommandType.StoredProcedure;
        string invoice = textBox.Text.TrimEnd();
        string parameter = string.Format("@invoice{0}", count);

        command.Parameters.AddWithValue(parameter, invoice);
        int invoiceCount = (int)command.ExecuteScalar();

        if (invoiceCount > 0)
        {

            lblError.Text = "Invoice number already exist";
            return;
        }
        command.Parameters.Clear();
    }

Would something like this work better as it factors in the two parameters. 这样的事情会更好地起作用,因为它将两个参数都考虑在内。

select count(*) as CountInvoice where invoice1=@invoice1 or invoice2=@invoice2


using (SqlCommand command = new SqlCommand("sp_Count", conn))
{

    foreach (TextBox textBox in placehldr1.Controls.OfType<TextBox>())
    {

        count1 += 1;
        count2 += 1;
        command.CommandType = CommandType.StoredProcedure;
        string invoice = textBox.Text.TrimEnd();
        string parameter1 = string.Format("@invoice1", count1);
        string parameter2 = string.Format("@invoice2", count2);
        command.Parameters.AddWithValue(parameter, invoice);
        int invoiceCount = (int)command.ExecuteScalar();

        if (invoiceCount > 0)
        {

            lblError.Text = "Invoice number already exist";
            return;
        }
        command.Parameters.Clear();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM