[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 163
  • Last Modified:

VB.net 1/SQL 2k: Nothing is returning from the DB using a WHERE clause with a date datatype.

I have a SQL 2k Table with a col of the smallDateTime dataType (MyDateCol). From my VB.net app, I want to fill my dataTable with all the records in that table that meet a date range. The dataAdapter has two parameters:
MyDataAdapter.SelectCommand.Parameters("@StartDate").Value = New Date(2007,1,1)
MyDataAdapter.SelectCommand.Parameters("@EndDate").Value = New Date(2007,12,31)

My VB App:
MyDataAdapter.SelectCommand.CommandText = "SELECT MyCols FROM MyDataBase.dbo.MyTable WHERE (MyDateCol>= @StartDate) OR (MyDateCol<= @EndDate)"

My Sql Table
Value of MyDateCol = '2007-07-25 11:45:00'

Upon calling the fill method, nothing is returned. The above WHERE date clauses surely catch the Sql date value, but how can I get it to be recognised and thus returned?

  • 2
  • 2
1 Solution
Try this.
In your WHERE clause "WHERE (MyDateCol>= @StartDate) OR (MyDateCol<= @EndDate)" change it to
WHERE (MyDateCol >= '@StartDate') OR (MyDateCol <= '@EndDate'). I handle my statements different than you but when dealing with the datetime type in SQL Server I have found that the value has to be surrounded by a single quote same as you would for a string value.

If you are looking to return value's between the two dates then you will have to change the OR to AND or you will return all values before the enddate and all values that come after the startdate. Keep us posted.

IvanHowarthAuthor Commented:
Visual Studio (2003) didn't like the quotes. Nevertheless, it wasn't the quotes that was the problem, it was the OR. Changing it to AND and leaving out the quotes worked. Thanks.

Before I award you the points...
I can't get the records where  MyDateCol = '2007-07-25 11:45:00' --i.e. today when
MyDataAdapter.SelectCommand.Parameters("@StartDate").Value = Date.Today
MyDataAdapter.SelectCommand.Parameters("@EndDate").Value = Date.Today
Only when I expand the range. Any ideas, or should I add a time to it e.g. 00:01 and 23:59 respectively?

I would add a time to it given that the value in your mydatecol does hold a real time. I have always used the shortdate version which defaults the time to 00:00.
IvanHowarthAuthor Commented:
Following that idea. Thanks again Dale!

Featured Post

Microsoft Certification Exam 74-409

VeeamĀ® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now