barsan
barsan

Reputation: 2491

How to compare only year from a datetime field in sql server 2008?

I have a table containing a datetime column named:

 TranDate

So, I have to query through the table to get the data depend on the year only. So, I am little bit confused about how to do this. My current sql query is:

 select * from Angkasa_UnpostedRecords 
 where year(convert(datetime,TranDate,103) = year(convert(datetime,@FromDate,103)

But I am getting error in this. Please suggest me how can I do this.

Thank you.

Upvotes: 6

Views: 35483

Answers (4)

Nisha
Nisha

Reputation: 1439

I think you could use just the year part

select * from Angkasa_UnpostedRecords 
 where year(TranDate) = year(@FromDate)

If TranDate and @FromDate are not datetime fields then

select * from Angkasa_UnpostedRecords 
 where year(convert(datetime,TranDate,103)) = year(convert(datetime,@FromDate,103))

with the opening and closing brackets.

Upvotes: 7

Amit
Amit

Reputation: 15387

Try this

select * from Angkasa_UnpostedRecords
WHERE DATEDIFF(year, TranDate, @FromDate)=0

Upvotes: 5

Colin Mackay
Colin Mackay

Reputation: 19175

The syntax error is because you've not closed the brackets properly. You open two, but close only one on each side of the equality operator

Upvotes: 12

CodingIntrigue
CodingIntrigue

Reputation: 78535

You are missing parenthesis:

 select * from Angkasa_UnpostedRecords 
 where year(convert(datetime,TranDate,103)) = year(convert(datetime,@FromDate,103))

Notice the extra bracket at the end of each year( function

Upvotes: 4

Related Questions