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). 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#?


SELECT [mydate] 
    FROM [table] 
    WHERE DATEPART(hh,[mydate]) >= 6 
        AND DATEPART(hh,[mydate]) <= 8 
    Order by DATEPART(hh,[mydate])

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;

    SqlDataReader reader = cmd.ExecuteReader();

    while (reader.Read())
        // up to you

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.

Need Your Help

MySQL: value based on conditions

sql mysql conditional

I have a MySQL query where I would like it to have a pseudo column returned which is based off of:

PHPImageWorkshop library: layering transparent PNG images

php png transparent layer

I am using the PHPImageWorkshop library to layer up transparent images, (which is one of the things it is supposed to excel at, so I must be doing it wrong)!