1

我得到了这段代码,SELECTS SUM然后UPDATE在某个地方得到了这个结果。但问题是什么时候有no results found for SELECT SUM(castka)这些条件。

我想知道Exception for DBNull如果没有找到任何结果,该怎么做UPDATE "0"。由于我的编程时间不长,有人可以帮我解决这个问题吗?

非常感谢您的参与。

private void btn_zavri_Click(object sender, EventArgs e)
    {
        try
        {

            spojeni.Close();
            SqlCommand sc2 = new SqlCommand("SELECT SUM(castka) AS sumcastka FROM kliplat WHERE akce='" + zakce.Text + "' AND rocnik='" + rocnik + "'", spojeni);
            spojeni.Open();
            int vysledek2 = Convert.ToInt32(sc2.ExecuteScalar());
            SqlCommand sc3 = new SqlCommand("UPDATE zajezd SET s_prijmy=@s_prijmy WHERE akce='" + zakce.Text + "' AND rocnik='" + rocnik + "'", spojeni);
            spojeni.Close();
            sc3.Parameters.AddWithValue("@s_prijmy", vysledek2);
            spojeni.Open();
            sc3.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show("" + ex);
        }
        finally
        {
            spojeni.Close();
            this.Close();
        }
    }
4

4 回答 4

1

这是你想要达到的目标吗?

SELECT ISNULL(SUM(castka), 0) AS sumcastka FROM kliplat
于 2013-08-13T09:47:00.633 回答
1
try
    {

        spojeni.Close();
        SqlCommand sc2 = new SqlCommand("SELECT SUM(castka) AS sumcastka FROM kliplat WHERE akce='" + zakce.Text + "' AND rocnik='" + rocnik + "'", spojeni);
        spojeni.Open();
        object obj = sc2.ExecuteScalar();
        int vysledek2 = obj == null ? 0  : Convert.ToInt32(obj);
        if(obj != null){
          SqlCommand sc3 = new SqlCommand("UPDATE zajezd SET s_prijmy=@s_prijmy WHERE akce='" + zakce.Text + "' AND rocnik='" + rocnik + "'", spojeni);
          spojeni.Close();
          sc3.Parameters.AddWithValue("@s_prijmy", vysledek2);
          spojeni.Open();
          sc3.ExecuteNonQuery();
        }
    }
//....
于 2013-08-13T09:47:22.307 回答
0

用 ISNULL 包裹 sum 函数,当没有记录时返回 0:

SELECT ISNULL(SUM(castka), 0) AS sumcastka
于 2013-08-13T09:51:07.113 回答
0

改变这个

  int vysledek2 = Convert.ToInt32(sc2.ExecuteScalar());

 object test = sc2.ExecuteScalar();
 if(test != DBNull.Value && test!=null)
 {
     //rest of your code
     int vysledek2 = Convert.ToInt32(test);
 }
于 2013-08-13T09:49:55.340 回答