Oh hi Mark
Oh hi Mark

Reputation: 203

Query an SQL Datetime Column using only part of the date

For example I have a column with these dates:

I want to query and return only rows with the year 2012, or month 05. The issue is that I'm not querying for the whole date but part of it. I'm using Entity Framework and C#.

This is what my code looks, it's not linq but it gets the job done.

using (var db = new Entity())
{
     foreach (var a in db.table)
     {
          if ((a.dateColumn.Value.Day == day)) //day is an int
          {
             //do stuff
          }
      }
 }

Upvotes: 0

Views: 113

Answers (2)

Arash
Arash

Reputation: 885

using lambda expression

YourTable.where(x=>x.Date.Year==2013)
YourTable.where(x=>x.Date.Month==5)

Upvotes: 1

Salah Akbari
Salah Akbari

Reputation: 39966

Something like this:

var x =(from c in db.Table
         where c.Date.Value.Year == 2012
         select c).ToList();

And for Month:

var y = (from c in db.Table
         where c.Date.Value.Month == 5
         select c).ToList();

Upvotes: 1

Related Questions