gpt4 book ai didi

SQL Server 操作数类型冲突 : date is incompatible with int

转载 作者:行者123 更新时间:2023-12-02 09:36:14 24 4
gpt4 key购买 nike

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

Msg 206, Level 16, State 2, Line 15
Operand type clash: date is incompatible with 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 选项,但如果您还不知道,我会推荐您 read this .基本上,在这种情况下,这意味着您可以使用 CTE 列出 1,000 个日期。如果您需要更多,则必须更改那 1000 个以满足您的需求。

关于SQL Server 操作数类型冲突 : date is incompatible with int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26019011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com