[英]Sql Server Operand type clash: date is incompatible with int
當我嘗試執行此代碼時,在“ with DateDimension”行出現錯誤:
訊息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列出1,000個日期。 如果您需要的更多,則必須將其更改為1000以符合您的需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.