0

我试图将日期和月份与年份连接起来,我需要检查每条记录以找到财政年度。当我执行查询时,它显示(将 varchar 数据类型转换为 datetime 数据类型导致值超出范围。)错误。请帮我找出问题所在。

代码

   set @SiteFileVal1='04-01'
   set @SiteFileVal2='03-31'
   set @SiteFileYear='2013'

   SELECT bb.Amount
   FROM Budget bb
   JOIN Invoice i ON i.AccountId=bb.AccountId
   WHERE bb.AccountId=i.AccountId
   AND bb.Year=
   (SELECT CASE WHEN (i.Date >= convert(datetime,@SiteFileVal1+'-'+convert(varchar(200),DATEPART(yyyy,i.Date)))
                   AND i.Date < convert(datetime,@SiteFileVal2+'-'+convert(varchar(200), DATEADD(yyyy,1,DATEPART(yyyy,i.Date))))) THEN year(@SiteFileYear) ELSE DATEADD(yyyy,-1,DATEPART(yyyy,i.Date)) END)
4

1 回答 1

1

这部分不正确:DATEADD(yyyy,-1,DATEPART(yyyy,i.Date))

DATEADD期望传入的日期,而您仅传入日期的年份-DATEPART(yyyy, i.Date)

使用您的代码,我做了:

select DATEADD(yyyy,-1,DATEPART(yyyy,'1/8/2007'));

结果?1904-07-01 00:00:00.000

当我重新添加一个月/一天时,这就是我得到的:

select DATEADD(yyyy,-1, CAST(DATEPART(mm, '1/8/2007') as varchar) + '/' + 
 CAST(DATEPART(DD, '1/8/2007') as varchar) + '/' + 
 cast(DATEPART(yyyy,'1/8/2007') as varchar))

结果:2006-01-08 00:00:00.000

这是对查询的大量解析,但这是您需要的,格式化为您的列。

set @SiteFileVal1='04-01'
set @SiteFileVal2='03-31'
set @SiteFileYear='2013'

SELECT bb.Amount
FROM Budget bb
JOIN Invoice i ON i.AccountId=bb.AccountId
 WHERE bb.AccountId=i.AccountId
  AND bb.Year=
DatePart(yyyy,
(CASE WHEN (i.Date >= convert(datetime,@SiteFileVal1+'-'+convert(varchar(200),DATEPART(yyyy,i.Date)))
               AND i.Date < convert(datetime,@SiteFileVal2+'-'+convert(varchar(200), DATEADD(yyyy,1,CAST(DATEPART(mm, i.Date) as varchar) + '/' +
      CAST(DATEPART(DD, i.Date) as varchar) + '/' + 
          cast(DATEPART(yyyy,i.Date) as varchar))))) 
          THEN year(@SiteFileYear) ELSE 
DATEADD(yyyy,-1, CAST(DATEPART(mm, i.Date) as varchar) + '/' +
      CAST(DATEPART(DD, i.Date) as varchar) + '/' + 
      cast(DATEPART(yyyy,i.Date) as varchar)) END) )
于 2013-10-03T04:42:01.017 回答