1

I am building a web application that is going to show the upcoming birthdays of a list of people stored in a SQL Server 2008 DB. I can't figure out how to query all records in the DB that are within 30 days of today's date.

Here's what I have so far:

using (HumanResourcesDB db = newH umanResourcesDB(ConfigurationManager.ConnectionStrings["HumanResourcesDB"].ConnectionString))
            {
                DateTime todaysDate = DateTime.Now;

                List<Employee> record =
                (from tab in db.Employees
                 where tab.Birthday between DateTime.Now and todaysDate.AddDays(30) 
                 select tab).ToList();
                this.grdBirthdays.DataSource = record;
                this.grdBirthdays.DataBind();
            }

of course the "between" and "and" don't work that's what I need filled in. I've searched the net for a little while to no avail. Any help?

1 Answer 1

4

Just use a greater than and less than

using (HumanResourcesDB db = newHumanResourcesDB(ConfigurationManager
            .ConnectionStrings["HumanResourcesDB"].ConnectionString))
{
    List<Employee> record = (from tab in db.Employees
     where tab.Birthday >= DateTime.Today
     && tab.Birthday < DateTime.Today.AddDays(31)
     select tab).ToList();

    this.grdBirthdays.DataSource = record;

    this.grdBirthdays.DataBind();
}

Also I should mention that I have used DateTime.Today rather than DateTime.Now because today represents the start of the day as 00:00:00.000. If someones birthday is set to whatever today is at 00:00:00.000 and you have used DateTime.Now (let's assume it's 8:00 in the morning). There birthday will not be included in this range because it is considered before "now".

Sign up to request clarification or add additional context in comments.

6 Comments

Then you understand that the end of the range should probably be < AddDays(31) not <= AddDays(30) - if someone's birthday is not set to midnight on the last day, they'll get excluded for the same reason.
I tried that earlier it gives a few errors. "The type or namespace name 'AND' could not be found" "A local variable named 'tab' cannot be declared in this scope because it would give a different meaning to 'tab', which is already used in a 'child'scope to denote something else"
@bromanguy Try to uncapitlize(spelling?) the AND make it lower case.
@JamesHay same error. Am I missing a library referenece or something?
Well I did copy and paste but then I deleted everything on that line after "where tab.Birthday". From there my SQL typing instinct kicked in and the rest is history.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.