Sql Server操作数类型冲突:日期与int不兼容

Sql Server操作数类型冲突:日期与int不兼容,sql,sql-server,Sql,Sql Server,当我尝试执行此代码时,在“with DateDimension”行出现错误: Msg 206,16级,状态2,第15行 操作数类型冲突:日期与int不兼容 这是我正在使用的SQL查询: declare @DateCalendarStart date, @DateCalendarEnd date, @FiscalCounter date, @FiscalMonthOffset int; set @DateCalendarStar

当我尝试执行此代码时,在“with DateDimension”行出现错误:

Msg 206,16级,状态2,第15行 操作数类型冲突:日期与int不兼容

这是我正在使用的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
)
您的问题在于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选项,但如果您还不知道,我会推荐您。基本上,在这种情况下,这意味着您可以用CTE列出1000个日期。如果您需要更多,您必须更改1000以满足您的需要

尝试用DATEADD函数替换DateCalendarValue+1。欢迎使用堆栈溢出!我们很高兴见到你:我建议你复习,以提高你的问题得到好答案的机会。如果有必要,您可以使用它添加注释部分中要求的更多详细信息。您是否可以编写更正的代码段,请单击“AllemanHappy”选项卡以获得帮助。如果这个或任何答案已经解决了你的问题,请考虑点击复选标记。这向更广泛的社区表明,你已经找到了一个解决方案,并给回答者和你自己带来了一些声誉。没有义务这样做。