[英]sql query for specific date interval
id name mydate
1 co 2011-02-10 07:25:02
2 Carl 2011-02-10 07:26:02
.
.
.
10000 Caroline 2011-02-18 22:44:08
I have a database like that, I wanna search through for a specified interval such as (1 hour). 我有一个这样的数据库,我想搜索指定的时间间隔,例如(1小时)。 For instance, I want to see the records between 07 AM and 08 AM among the all records for all days.
例如,我想查看全天所有记录中的07 AM到08 AM之间的记录。 And then, I will use each day's 7 AM and 8 AM for further process.
然后,我将使用每天的上午7点和上午8点进行进一步的处理。 How can I do that in C#?
如何在C#中做到这一点?
You can use the BETWEEN keyword. 您可以使用BETWEEN关键字。
SELECT * FROM A WHERE mydate between '1/1/56 07:00:00' and '12/31/57 08:00:00'
This is not C# specific. 这不是特定于C#的。 If your using LINQ it something like this:
如果您使用LINQ,则如下所示:
from mt in ctx.MyTable where mydate >= datestart and mydate <= stopdate select mt
In this case ctx is the context, startdate the lower date and stopdate the higher and. 在这种情况下,ctx是上下文,startdate的日期较低,而stopdate的日期较高。
If you want to read the result using ADO.NET: 如果要使用ADO.NET读取结果:
var cn = new SqlConnection("paste your code here");
SqlCommand command = new SqlCommand();
cmd.CommandText = "SELECT * FROM A WHERE mydate between '1/1/56 07:00:00' and '12/31/57 08:00:00'";
cmd.Connection = cn;
try
{
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// up to you
}
reader.Close();
}
finally
{
cn.Close();
}
SELECT [mydate]
FROM [table]
WHERE DATEPART(hh,[mydate]) >= 6
AND DATEPART(hh,[mydate]) <= 8
Order by DATEPART(hh,[mydate])
SELECT * FROM table
WHERE DATEPART(hh, mydate) = @start
OR (DATEPART(hh, mydate) = @end AND DATEPART(mi, mydate) = 0)
ORDER BY mydate
DATEPART
is a SQL function that gets the specified portion of the date given the date value. DATEPART
是一个SQL函数,该函数获取给定日期值的日期的指定部分。 In the sql script above, @start and @end are the integer values of the starting hours, in the case of 7AM to 8AM, @start = 7 and @end = 8. 在上面的sql脚本中,@start和@end是开始时间的整数值,对于从7AM到8AM的情况,@ start = 7和@end = 8。
Essentially, you're getting all records from your table that has a date with the hour component equal to 7 or a date with the hour component equal to 8 and with the minute component equal to 0. This should get all records between 7:00 AM to 8:00 AM inclusive. 本质上,您将从表中获得所有记录,这些记录的日期中的小时部分等于7,或者日期中的小时部分等于8,分钟部分等于0。这应该获取7:00之间的所有记录。上午至8:00(含)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.