Skip to main content
December 3, 2012
Question

searching between dates with "where" in msSQL

  • December 3, 2012
  • 2 replies
  • 1804 views

i have a table that has two date fields (dateinx and dateoutx) and i need to find all the results for todays date that both fall between and on that date for a given customer: cID.

if todays date is 12/2/2012

examples of vialable entries:

dateinx=12/2/2012 and dateoutx = 12/5/2012

dateinx=11/2/2012 and dateoutx = 12/2/2012

dateinx=11/2/2012 and dateoutx = 12/25/2012

i am using "smalldatetime" in msSQL2005 and also would like to create a mask so that only date: 1/1/2012 would be saved.

same for time: 1:30AM in a seperate field. msSQL is saving now as 1/1/2012 01:30:00AM or some such...

querey at this point looks like:

SELECT *

FROM schdl

WHERE (cID = #cID#) AND ....

tnx in advance

andy

This topic has been closed for replies.

2 replies

BKBK
Community Expert
Community Expert
December 7, 2012

ranger wrote:


... i am using "smalldatetime" in msSQL2005 and also would like to create a mask so that only date: 1/1/2012 would be saved.

... same for time: 1:30AM in a seperate field. msSQL is saving now as 1/1/2012 01:30:00AM or some such...

The Smalldatetime type is of the form YYYY-MM-DD hh:mm:ss. If you wish to save just the date, then use the Date type. That is of the form YYYY-MM-DD. The Time type is of the form hh:mm:ss.

Where necessary, use SQL Server's datetime functions like convert() to get the right format. For example, suppose you had saved the date in the columns dateinx and dateoutx as Date type YYYY-MM-DD. Then you could do something like this

SELECT *

FROM schedule

WHERE dateinx <= convert(Date, getdate(), 101) AND dateoutx >= convert(Date, getdate(), 101)

Inspiring
December 3, 2012

If you want to separate the date and time components you have to upgrade to a later version of mssql. 

To do your search, use this logic:

and yourdatefield >= date1

and yourdatefield < the day after date 2.

Don't worry about date formats.  Dates are actually numbers.  There are functions both in sql server and coldfusion that enable you to format these.

December 5, 2012

tnx Dan,

think this does it unless i'm missing something

WHERE tdate1 <= ('#DateFormat(NOW())#') AND

   (tdate2 >= '#DateFormat(NOW())#')

Inspiring
December 5, 2012

Dateformat returns a string.  The only time to use it is for display purposes. 

Since your db is sql server, I wouldn't even pass use a ColdFusion variable.  I'd use GetDate().