[英]Combining similar methods
我目前有兩種方法:
CalculateDaily()
{
List<string> tempList;
// Effective query. not what is really passed
tempList = "SELECT timestamp FROM table1 WHERE date = today";
var total = tempList.Sum();
}
和:
CalculateTotal()
{
List<string> tempList;
// Effective query. not what is really passed
tempList = "SELECT timestamp FROM table1"
var total = tempList.Sum();
}
我的問題是我應該將它們分開,還是將它們組合為一個方法並運行if
檢查是否可行? 就像是:
Calculate(bool daily)
{
List<string> tempList;
if(daily)
tempList = "SELECT timestamp FROM table1 WHERE date = today";
else
tempList = "SELECT timestamp FROM table1";
var total = tempList.Sum();
}
我將使用提供開始日期和結束日期的方法。 然后,您可以根據需要使用它。
public static int Calculate(DateTime startDate, DateTime endDate)
{
string sql = @"SELECT SUM(timestamp)
FROM table1
WHERE date BETWEEN @startDate AND @endDate";
using(var con=new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, con))
{
con.Open();
cmd.Parameters.AddWithValue("@startDate", startDate);
cmd.Parameters.AddWithValue("@endDate", endDate);
int sum = (int)cmd.ExecuteScalar();
return sum;
}
}
我會這樣:
Calculate(bool daily)
{
List<string> tempList;
tempList = "SELECT timestamp FROM table1"
if(daily)
tempList += " WHERE date = today";
var total = tempList.Sum();
}
或更參數化的版本(一些偽代碼):
Calculate(bool daily)
{
List<string> tempList;
tempList = "SELECT timestamp FROM table1 WHERE (@Date IS NULL OR date = @Date)"
if(daily)
@Date = today;
else
@Date = null;
var total = tempList.Sum();
}
怎么樣...
Calculate(bool daily)
{
List<string> tempList;
tempList = "SELECT timestamp FROM table1";
if(daily)
tempList += " WHERE date = today";
var total = tempList.Sum();
}
盡管“有效查詢”部分需要澄清。
您可以為標量查詢創建通用方法
// Assumes parameter names @0, @1, @2 ... in the query.
public static T ExecuteScalar<T>(string query, params object[] parameters)
{
using(var conn = new SqlConnection(myConnectionString))
using (var cmd = new SqlCommand(query, conn)) {
for (int i = 0; i < parameters.Length; i++) {
cmd.Parameters.AddWithValue("@" + i, parameters[i]);
}
conn.Open();
return (T)cmd.ExecuteScalar();
}
}
然后為您的查詢創建重載方法
public static decimal SumTable1Amount()
{
return ExecuteScalar<decimal>("SELECT SUM(amount) FROM table1");
}
public static decimal SumTable1Amount(DateTime date)
{
return ExecuteScalar<decimal>(
"SELECT SUM(amount) FROM table1 WHERE date = @0",
date);
}
public static decimal SumTable1Amount(DateTime fistDate, DateTime lastDate)
{
return ExecuteScalar<decimal>(
"SELECT SUM(amount) FROM table1 WHERE date BETWEEN @0 AND @1",
fistDate, lastDate);
}
現在,調用不同的查詢非常容易,因此不再需要創建單個參數化方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.