简体   繁体   中英

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.

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

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.

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

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM