Question

[Solved] Sql Server Operand type clash: date is incompatible with int

When I try to execute this code I get an error at the ‘with DateDimension’ line:

Msg 206, Level 16, State 2, Line 15
Operand type clash: date is incompatible with int

This is the SQL query I am using:

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
)

Solution #1:

Your problem is with the DateCalendarValue + 1 portion. Try using DATEADD(), as below:

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)

EDIT: I don’t know if your original code was going to use the MAXRECURSION option or not, but if you didn’t know already I would recommend you read this. Basically, in this circumstance it means that you can list out 1,000 dates with the CTE. If you need more than that, you’ll have to change that 1000 to match your needs.

Respondent: AHiggins

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy