比较WHERE子句中的YEAR值

时间:2015-08-18 01:54:23

标签: tsql sql-server-2008-r2

使用SQL Server 2008 R2我试图比较where子句中的年份值,如下所示:

AND year(convert(date, (LEFT(formAuditLog, 10)), 104 )) = year(GETDATE())

但是我收到了这个错误:

  

从字符串

转换日期和/或时间时转换失败

我也试过这个但得到了同样的结果:

AND cast(year(convert(date, (LEFT(formAuditLog, 10)), 104 )) as int) = cast(year(GETDATE()) AS INT)

注意 - formAuditLog是一个字符串。我得到前10个字符总是mm/dd/yyyy(我已经三次检查了这个)所以我转换为日期然后得到这一年。根据这些信息,我不能进行这种比较吗?

提前致谢

补充: 注意 - 当我把它放在一个选择它工作。我得到了我期待的年份部分:

select top 10 year(convert(date, (LEFT(formAuditLog, 10)), 104 )) , * from myTableName 

那么为什么在select中允许这个但在where子句中失败呢?

补充:为了完整性,本文顶部的两个SQL位中的任何一个都没有错。正如下面接受的帖子评论中所提到的,它是一个formAuditLog记录中的一个主要引用,导致它崩溃

2 个答案:

答案 0 :(得分:1)

如果您的formAuditLog列是您建议的字符串,则左侧10个字符相当于日期格式MM/DD/YYYY。这应该适合你:

create table mytableName (id int, formAuditLog varchar(50));

insert into mytableName values
(1,'01/02/20141203'),
(2,'01/03/20151203'),
(3,'05/01/20151203');


select 
      id,
      formAuditLog,
      cast(left(formAuditLog,10) as date) as DateField,
      year(cast(left(formAuditLog,10) as date)) as yearfield
from mytableName
where year(cast(left(formAuditLog,10) as date)) = year(cast(getdate() as date));

Code Demo

答案 1 :(得分:0)

对于sql server 2008,这应该是您的where条件

    and year(GETDATE()) = case when isdate(LEFT(formAuditLog, 10))=1 then year(convert(date, (LEFT(formAuditLog, 10)))) else  99999 end

对于sql server 2012 ..

 AND  year(  try_parse(LEFT(formAuditLog, 10) as date)  ) = year(GETDATE())