简体   繁体   English

如何仅比较sql server 2008中的datetime字段的年份?

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

I have a table containing a datetime column named: 我有一个包含datetime列的表,名为:

 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: 我当前的SQL查询是:

 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 如果TranDate和@FromDate不是日期时间字段

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 注意year(年底的额外支架year(功能

Try this 尝试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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