[英]c#, build sql to select a user given an age range
我有一個人才表,其中包含所有用戶,其中有一個列其生日的列。 在指定年齡段內才能的最佳方式是什么? 這是我所擁有的,但似乎要過幾天。 有沒有更好的辦法?
// BUILD SQL FROM FORM DATA
sqlString += "SELECT * from Talent";
if (minAge != 0 || maxAge != 120)
{
// The age criteria has been change, filter by age.
// select all talents that have birthdays between the following 2 dates.
DateTime startDate = (DateTime.Now - new TimeSpan((maxAge * 365), 0, 0, 0)); // maxAge * 365 = totalDays
DateTime endDate = (DateTime.Now - new TimeSpan((minAge * 365), 0, 0, 0));
sqlString += " WHERE Birthdate BETWEEN '" + startDate.ToString() + "' AND '" + endDate.ToString() + "'";
}
假設您正在使用SQL Server ...
using (var connection = new SqlConnection(connString))
using (var command = connection.CreateCommand()) {
string tsql = @"
select *
from Talent
where DATEDIFF(YEAR, BirthDay, GETDATE()) BETWEEN @minAge AND @maxAge";
command.CommandText = tsql;
command.CommandType = CommandType.Text;
int minAge = 1;
int maxAge = 120;
SqlParameter minAgeParam = command.CreateParameter();
minAgeParam.Direction = ParameterDirection.Input;
minAgeParam.DbType = SqlDbType.TinyInt;
minAgeParam.ParameterName = "@minAge";
minAgeParam.Value = minAge;
SqlParameter maxAgeParam = command.CreateParameter();
maxAgeParam.Direction = ParameterDirection.Input;
maxAgeParam.DbType = SqlDbType.TinyInt;
maxAgeParam.ParameterName = "@maxAge";
maxAgeParam.Value = maxAge;
// Just unsure here whether I must add the parameters to the command,
// or if they are already part of it since I used the
// SqlCommand.CreateParameter() method.
// Been too long since I haven't done any ADO.NET
command.Parameters.Add(minAgeParam);
command.Parameters.Add(maxAgeParam);
connection.Open();
SqlDataReader reader = null;
try {
reader = command.ExecuteReader();
// Process your records here...
} finally {
connection.Close()
command.Dispose();
connection.Dispose();
if (reader != null) {
reader.Dispose();
}
}
}
其中@minAge和@maxAge是您的年齡參數。
您還可以告訴DATEDIFF
TSQL函數考慮天,月,小時,分鍾,秒等的差異。因此,您將必須相應地轉換參數值。
就個人而言,我發現使用startDate.ToString("yy-MM-dd 00:00:00.000")
和endDate.ToString("yy-MM-dd 23:59:59.000")
效果最佳(請注意,出於某種原因,以我的經驗,當涉及到范圍時,sql已關閉(可能是由於某種舍入錯誤所致)。
TimeSpan
,您可以使用TimeSpan
對象中的靜態方法進行時間計算。 例如TimeSpan.FromDays(...)
問題可能與DateTime.Now
有關,后者考慮了時間和日期。 嘗試將其替換為DateTime.Today
。
為什么不使用DateTime.AddYears方法。
DateTime startDate = DateTime.Now.AddYears(-maxAge);
的
DateTime startDate = (DateTime.Now - new TimeSpan((maxAge * 365), 0, 0, 0));
另一件事是:請不要在字符串之間使用+
運算符來構建sql查詢,而應使用StringBuilder
。
物有所值-您的原始解決方案將用幾天的時間,因為它使用365而不是計算leap年。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.