Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 533
barsan Avatar asked Aug 19 '13 08:08

barsan


People also ask

How do I select year from datetime in SQL?

You can use year() function in sql to get the year from the specified date.

How can I compare only date parts in SQL Server?

To compare dates without the time part, don't use the DATEDIFF() or any other function on both sides of the comparison in a WHERE clause. Instead, put CAST() on the parameter and compare using >= and < operators. Let's use StackOverflow database to find all user profiles created on a particular date.

How can I compare two date years in SQL?

This can be easily done using equals to(=), less than(<), and greater than(>) operators. In SQL, the date value has DATE datatype which accepts date in 'yyyy-mm-dd' format. To compare two dates, we will declare two dates and compare them using the IF-ELSE statement.


2 Answers

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

like image 113
Colin Mackay Avatar answered Oct 29 '22 12:10

Colin Mackay


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.

like image 38
Nisha Avatar answered Oct 29 '22 13:10

Nisha