当我使用日期类型变量而不是硬编码日期时,为什么会出现 "Operand type clash: date is incompatible with int" 错误?
Why am I getting "Operand type clash: date is incompatible with int" error when I use a date type variable instead of hard coded date?
当我在 WHILE 循环提到的条件中使用日期变量而不是硬编码日期时,为什么会出现 "Operand type clash: date is incompatible with int" 错误,我有点困惑。
Declare @ddate date='2013-03-25', @MembershipDate date= '2013-03-27',@id int=0
while (@ddate<=DATEADD(mm,3,@MembershipDate)-1)
begin
set @id=@id+1
end
但是如果我像下面提到的那样直接使用硬编码日期,那么我不会收到任何错误
Declare @ddate date='2013-03-25',@id int=0
while (@ddate<=DATEADD(mm,3,'2013-03-27')-1)
begin
set @id=@id+1
end
请告诉我原因。
因为当您使用字符串时,它会隐式转换为日期时间,DATEADD
的结果是日期时间。
当您使用日期时,DATEADD
的结果是日期。
这是在the docs
中指定的
DATEADD (datepart , number , date )
The date
argument data type becomes the DATEADD return value data
type, except for string literal date values. For a string literal,
DATEADD returns a datetime value.
较新的日期和时间数据类型不支持此类算术。您可以使用 DATEADD
与 day
和 -1
从中减去一天。反正这样比较清楚。
当我在 WHILE 循环提到的条件中使用日期变量而不是硬编码日期时,为什么会出现 "Operand type clash: date is incompatible with int" 错误,我有点困惑。
Declare @ddate date='2013-03-25', @MembershipDate date= '2013-03-27',@id int=0
while (@ddate<=DATEADD(mm,3,@MembershipDate)-1)
begin
set @id=@id+1
end
但是如果我像下面提到的那样直接使用硬编码日期,那么我不会收到任何错误
Declare @ddate date='2013-03-25',@id int=0
while (@ddate<=DATEADD(mm,3,'2013-03-27')-1)
begin
set @id=@id+1
end
请告诉我原因。
因为当您使用字符串时,它会隐式转换为日期时间,DATEADD
的结果是日期时间。
当您使用日期时,DATEADD
的结果是日期。
这是在the docs
中指定的
DATEADD (datepart , number , date )
The
date
argument data type becomes the DATEADD return value data type, except for string literal date values. For a string literal, DATEADD returns a datetime value.
较新的日期和时间数据类型不支持此类算术。您可以使用 DATEADD
与 day
和 -1
从中减去一天。反正这样比较清楚。