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 2008 Forums
 Transact-SQL (2008)
 Get data by year from DateTime

Author  Topic 

krainov
Yak Posting Veteran

57 Posts

Posted - 2010-06-08 : 04:13:01
Hi there!
I have a table where I store records (magazine issues) that have the IssueDate field (DateTime type). I want to retrieve the issues of the specific year by passing the parameter year as DateTime to the procedure. Lets say that the arameter is 10/10/1020 and I need to get all the records (issues) that belongs to the 1020th year.
What do I do?

Thanks!

pk_bohra
Master Smack Fu Yak Hacker

1182 Posts

Posted - 2010-06-08 : 04:21:51
Since the field is of DateTime datatype, you can use the Year function..

Example:

Select * from yourTable where Year(DateTimeField) = 2010
I feel it should work but i didn't carried out any testing.

Regards,
Bohra


I am here to learn from Masters and help new bees in learning.
Go to Top of Page

krainov
Yak Posting Veteran

57 Posts

Posted - 2010-06-08 : 04:28:31
And waht is the difference if I use the DatePart(year, MyDateParameter) ?
Go to Top of Page

senthil_nagore
Master Smack Fu Yak Hacker

1007 Posts

Posted - 2010-06-08 : 04:37:39
Select * from yourTable where Year(DateTimeField) = year(@year_parameter)

You can use datepart() too..

Senthil.C
------------------------------------------------------
[Microsoft][ODBC SQL Server Driver]Operation canceled

http://senthilnagore.blogspot.com/
Go to Top of Page

krainov
Yak Posting Veteran

57 Posts

Posted - 2010-06-08 : 04:45:35
quote:
Originally posted by pk_bohra

Since the field is of DateTime datatype, you can use the Year function..

Example:

Select * from yourTable where Year(DateTimeField) = 2010
I feel it should work but i didn't carried out any testing.

Regards,
Bohra


I am here to learn from Masters and help new bees in learning.



Thanks!
Go to Top of Page

krainov
Yak Posting Veteran

57 Posts

Posted - 2010-06-08 : 04:45:55
quote:
Originally posted by senthil_nagore

Select * from yourTable where Year(DateTimeField) = year(@year_parameter)

You can use datepart() too..

Senthil.C
------------------------------------------------------
[Microsoft][ODBC SQL Server Driver]Operation canceled

http://senthilnagore.blogspot.com/




Thanks!
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-06-08 : 05:04:42
To make use of index, use

Select * from yourTable
where
DateTimeField >= dateadd(year,datediff(year,0,@year_parameter),0) and
DateTimeField < dateadd(year,datediff(year,0,@year_parameter)+1,0)


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -