Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Selecting a month

Author  Topic 

AMB
Starting Member

6 Posts

Posted - 2006-10-16 : 10:59:39
Hi,
I am new to SQL and currently select some data from a table by using the date constraint below:

WHERE (DOCDATE BETWEEN '10/01/06' AND '10/31/06')

Is there a better way of selecting the month and year?



Thanks,
Andy.

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2006-10-16 : 11:04:14
you can also use

where docdate >= '20061001'
and docdate < '20061101'


Refer to http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=64762 for more information on datetime handling


KH

Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2006-10-16 : 11:04:39
"Is there a better way of selecting the month and year?"

That looks fine, however:

In order for your "text" dates to be unambiguous you should use 'yyyymmdd' format

Dates in SQL Server can include a time, so you would be better off using:

WHERE (DOCDATE >= '20061001' AND DOCDATE < '20061101')

There are functions you can use to manipulate dates - so if, for example, you have a parameter for the Start Date then you can use a function to calculate the first day of next month as your "limit"

There are also functions that will let you extract the Year / Month from a date, however using these will prevent the use of any index on the Date column, and thus SQL Server will be slower, so you are better off with the BETWEEN or ">= AND <" approach because that will effectively use an index on the date column, if available.

Kristen
Go to Top of Page
   

- Advertisement -