2014-09-24 52 views
0

不相容当我试图在“与DateDimension”行来执行这个代码,我得到一个错误:Sql Server的操作数类型冲突:日期与诠释

消息206,级别16,状态2,第15行
操作数类型冲突:日期与诠释

这不兼容是我使用的SQL查询:

declare @DateCalendarStart date, 
     @DateCalendarEnd date, 
     @FiscalCounter  date, 
     @FiscalMonthOffset int; 

set @DateCalendarStart = '2011-01-28'; 
set @DateCalendarEnd = '2012-10-26'; 


set @FiscalMonthOffset = 3; 

with DateDimension //Error got this line 

as 

(
    select @DateCalendarStart as DateCalendarValue, 
      dateadd(m, @FiscalMonthOffset, @DateCalendarStart) as FiscalCounter 

    union all 

    select DateCalendarValue + 1, 
      dateadd(m, @FiscalMonthOffset, (DateCalendarValue + 1)) as FiscalCounter 
    from DateDimension 
    where DateCalendarValue + 1 < = @DateCalendarEnd 
) 
+1

尝试用DATEADD函数替换“DateCalendarValue + 1”。 – 2014-09-24 14:13:24

+0

欢迎来到Stack Overflow!我们很高兴见到你:)我建议你复习[this](http://stackoverflow.com/help/how-to-ask),以提高你的问题得到一个好答案的机会。 [在你的问题下有一个'编辑'按钮](http://stackoverflow.com/help/editing),如果需要的话,你可以使用它来添加评论部分中所要求的更多细节。 – AHiggins 2014-09-24 14:13:53

+0

你能否写出正确的代码段请Tab Alleman – 2014-09-24 14:15:12

回答

4

你的问题是与DateCalendarValue + 1部分。尝试使用DATEADD(),如下:

declare @DateCalendarStart date, 
     @DateCalendarEnd date, 
     @FiscalCounter  date, 
     @FiscalMonthOffset int; 

set @DateCalendarStart = '2011-01-28'; 
set @DateCalendarEnd = '2012-10-26'; 

-- Set this to the number of months to add or extract to the current date to get the beginning 
-- of the Fiscal Year. Example: If the Fiscal Year begins July 1, assign the value of 6 
-- to the @FiscalMonthOffset variable. Negative values are also allowed, thus if your 
-- 2012 Fiscal Year begins in July of 2011, assign a value of -6. 
set @FiscalMonthOffset = 3; 

with DateDimension 

as 

(
    select @DateCalendarStart as DateCalendarValue, 
      dateadd(m, @FiscalMonthOffset, @DateCalendarStart) as FiscalCounter 

    union all 

    select DATEADD(DAY, 1, DateCalendarValue), -- Using a DATEADD() function here works for SQL Server 
      DATEADD(m, @FiscalMonthOffset, (DATEADD(DAY, 1, DateCalendarValue))) as FiscalCounter 
    from DateDimension 
    where DATEADD(DAY, 1, DateCalendarValue) < = @DateCalendarEnd 
) 

SELECT * FROM DateDimension OPTION (MAXRECURSION 1000) 

编辑:我不知道,如果你的原代码将使用MAXRECURSION选项或没有,但如果你还不知道我会建议你read this。基本上,在这种情况下,这意味着您可以在CTE中列出1,000个日期。如果您需要的不仅仅是这些,您需要更改1000以符合您的需求。

+0

非常感谢你的工作 – 2014-09-24 14:22:07

+0

乐意提供帮助。如果这个或任何答案已解决您的问题,请点击复选标记考虑[接受它](http://meta.stackexchange.com/q/5234/179419)。这向更广泛的社区表明,您已经找到了解决方案,并为答复者和您自己提供了一些声誉。没有义务这样做。 – AHiggins 2014-09-24 14:23:57

相关问题