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). For instance, I want to see the records between 07 AM and 08 AM among the all records for all days. And then, I will use each day's 7 AM and 8 AM for further process. How can I do that in C#?
You can use the BETWEEN keyword.
SELECT * FROM A WHERE mydate between '1/1/56 07:00:00' and '12/31/57 08:00:00'
This is not C# specific. If your using LINQ it something like this:
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.
If you want to read the result using 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. 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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.