我正在尝试编写一个方法,它从两个日期之间的条目中返回一列的总和。然而,无论如何,它都会不断返回DBnull
。我有其他类似的方法在查询更简单时工作(没有SUM,简单select * where statement
)。 performQuery()
只是一个帮助方法,它返回带有查询结果的填充datatable
。
public static int getBookedQuantity(int shopID, int bikeID, DateTime datetime)
{
string query = "SELECT sum(quantity) as \"quantity\" FROM booking WHERE bikeID=@bikeID AND shopID = @shopID AND starttime >= @Datetime AND endtime < @Datetime";
SqlParameter param1 = new SqlParameter("@bikeID", bikeID);
SqlParameter param2 = new SqlParameter("@shopID", shopID);
SqlParameter param3 = new SqlParameter("@Datetime", SqlDbType.DateTime);
param3.Value = datetime;
DataTable bookingData = performQuery(query, param1, param2, param3);
DataRow[] row = bookingData.Select();
int totalBooked = 0;
if ((row.Count()) > 0 && (bookingData != null)) // if there are rows returned
totalBooked = Convert.ToInt32(row[0]["quantity"]);
return totalBooked;
}
提前谢谢!
答案 0 :(得分:0)
尝试将查询修改为
string query = "SELECT sum(quantity) as 'quantity' FROM booking WHERE bikeID=@bikeID AND shopID = @shopID AND starttime >= @Datetime AND endtime < @Datetime";
答案 1 :(得分:0)
DataTable不是获得总和的正确方法。要解决您的问题,您必须这样做:
var sum = Convert.ToInt32(bookingData.Rows[0]["quantity"]);
return sum;
但是,执行此命令的正确方法是:
var statement = "SELECT COUNT(*) ...";
var command = new SqlCommand(statement, connection);
command.AddParam(param1);
command.AddParam(param2);
command.AddParam(param3);
var sum = Convert.ToInt32(command.ExecuteScalar());
return sum;
请参阅有关标量的MSDN文档:https://msdn.microsoft.com/it-it/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
希望这可以提供帮助。