得到错误的返回,SQL - if

本文关键字:SQL if 返回 错误 | 更新日期: 2023-09-27 18:02:25

我有下一个方法:

    private bool bla()
{
    int Minbuy, ordersTillNow;
    {
        SqlConnection connection = new SqlConnection("Data Source=****;Initial Catalog=****;User ID=****;Password=****;Integrated Security=False;");
        string commandtext = "SELECT Minbuy FROM items WHERE main = 1";
        string commandtext2 = "SELECT ordersTillNow FROM items WHERE main = 1";
        SqlCommand command = new SqlCommand(commandtext, connection);
        SqlCommand command2 = new SqlCommand(commandtext2, connection);
        connection.Open();
        Minbuy = (int)command.ExecuteScalar();
        ordersTillNow = (int)command2.ExecuteScalar();
        if (Minbuy < ordersTillNow)
            return true;
        else
            return false;
    }

}

和page_load:

方法的使用
        if (bla())
    {
        Image_V.Visible = true;
    }
    else
    {
       Image_X.Visible = true;
    }

SQL中查询结果的值为:

MinBuy = 5

ordersTillNow = 1

奇怪的是-不要介意db中的值是什么(我已经将值更改为:MinBuy = 1和ordersTillNow = 8) -它显示了image_v。(在aspx页面上-两个图像可见设置为false)。

代码有什么问题?

表格设计:

表名:items

columns: itemId(int), main (bit), MinBuy (int), ordersTillNow(int) .

得到错误的返回,SQL - if

我认为问题可能是上述SQL的结果可能返回多于1行。因此,它将给出错误的结果。

尝试将代码更改为:

string commandtext = "SELECT TOP 1 Minbuy FROM items WHERE main = 1";
string commandtext2 = "SELECT TOP 1 ordersTillNow FROM items WHERE main = 1";

可以用一个select

代替2个select
string queryString = "SELECT Minbuy, ordersTillsNow FROM items WHERE main = 1";
using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        connection.Open();
        SqlCommand command = new SqlCommand(queryString, connection);
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            MinBuy = int.Parse(reader[0].ToString());
            ordersTillsNow = int.Parse(reader[1].ToString());
            //Console.WriteLine(String.Format("{0}", reader[0]));
        }
    }

也许你需要:

if (bla())
{
    Image_V.Visible = true;
    Image_X.Visible = false;
}
else
{
   Image_V.Visible = false;
   Image_X.Visible = true;
}

那么,让我们只访问一次数据库,并让它为我们回答这个问题:

private bool bla()
{
    using(SqlConnection connection = new SqlConnection("Data Source=****;Initial Catalog=****;User ID=****;Password=****;Integrated Security=False;"))
    {
        string commandtext = "SELECT CONVERT(bit,CASE WHEN Minbuy < ordersTillNow THEN 1 ELSE 0 END) FROM items WHERE main = 1";
        SqlCommand command = new SqlCommand(commandtext, connection);
        connection.Open();
        return (bool)command.ExecuteScalar();    
    }
}

此代码还确保关闭连接,这是您之前没有注意到的。但是,如果您仍然没有看到预期的结果,那么就像其他人建议的那样,您需要检查图像显示代码是否按预期工作。也许有:

Image_V.Visible = bla();
Image_X.Visible = !Image_V.Visible;