0

当我在我的数据库上执行此命令时,有时会收到 result=null。我想在发生这种情况时输入“其他”部分,但我收到

mscorlib.dll 中发生了“System.FormatException”类型的未处理异常。附加信息:输入字符串的格式不正确。

DB database = new DB();
            int reservedSeats = 0;
            using (database.sqlConnection)
            {
                database.sqlConnection.Open();
                string command = "select SUM(nrLocuri) as result from Rezervari where idRand = @idRand and idShow=@idShow";
                using (SqlCommand cmd = new SqlCommand(command, database.sqlConnection))
                {
                    cmd.Parameters.Add("@idRand", SqlDbType.Int).Value = idRand;
                    cmd.Parameters.Add("@idShow", SqlDbType.Int).Value = idShow;
                    using (SqlDataReader dr = cmd.ExecuteReader())
                    {
                        if (dr.Read())
                            if (dr["result"].ToString() != null)
                                reservedSeats = Convert.ToInt32(dr["result"].ToString());
                            else
                                return totalSeats;
                    }
                }
            }
            return totalSeats-reservedSeats; 
4

4 回答 4

6

代替:

if (dr["result"].ToString() != null)

做:

if (dr["result"] != DbNull.Value)

dr["result"]返回一个数据库null时,它的值为DbNull.Value- 当你尝试调用Convert.ToInt32这个值时,你会得到一个格式异常。

于 2012-05-13T08:34:47.133 回答
2

尝试:

if(!dr.IsDBNull(i)){   //replace i with the column id

  //get the data

}
于 2012-05-13T08:38:59.370 回答
1

如果您想在未找到记录的情况下SUM()返回0.00,请将其替换为:

COALESCE(SUM(...), 0.00)

COALESCE 将返回传递给它的第一个非空值。

于 2012-05-13T08:35:44.603 回答
1

尝试isnull

string command = "select isnull(SUM(nrLocuri),0.00 )as result from Rezervari where idRand = @idRand and idShow=@idShow";
于 2012-05-13T08:38:46.120 回答