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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Get records by month

Author  Topic 

shapper
Constraint Violating Yak Guru

450 Posts

Posted - 2007-03-20 : 13:11:28
Hello,

I have a table where one of the columns is of type DATETIME.

I need to select all records for a given month (example: May 2005)
How should I pass the parameter and how can I select these records?

Thanks,
Miguel

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2007-03-20 : 13:17:05
[code]
Select
*
from
MyTable
where
-- Select all data from Feb, 2007
MyDate >= '20070201' and MyDate < '20070301'
[/code]

CODO ERGO SUM
Go to Top of Page

shapper
Constraint Violating Yak Guru

450 Posts

Posted - 2007-03-20 : 13:30:31
But isn't there a way to receive a DateTime parameter, retrieve the month and year in it and then get all records for that month.

For example, in my .NET code I would send a DATETIME as follows:
1 of Feb of 2007, 0:00 ...

Then my SQL code would get all the records in Feb 2007.

Of course, the result would be the same, If I would provide:
10 of Feb of 2007, 12:45

Thank You,
Miguel
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2007-03-20 : 13:40:41
quote:
Originally posted by shapper

But isn't there a way to receive a DateTime parameter, retrieve the month and year in it and then get all records for that month...



declare @MyMonth datetime
set @MyMonth = '20070201'

Select
*
from
MyTable
where
-- Select all data from Feb, 2007
MyDate >= @MyMonth and MyDate < dateadd(month,1,@MyMonth)


CODO ERGO SUM
Go to Top of Page
   

- Advertisement -