How to compare only year from datetime field in SQL Server 2008?

I have a table containing a datetime column with the name:

TranDate 

So, I have to query through the table so that the data depends only on the year. So, I am a little confused about how to do this. My current SQL query:

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

But I get an error in this. Please suggest me how I can do this.

Thanks.

+4
source share
4 answers

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

+12
source

Missing brackets:

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

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

+4
source

try it

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

I think you could use only part of the year

 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 opening and closing brackets.

+4
source

Source: https://habr.com/ru/post/1497744/


All Articles