操作数数据类型日期对于减法运算符无效

时间:2014-08-22 15:39:24

标签: sql-server function

我的表中有一个名为[LastDate] with DataType Date的字段。我将编写一个计算[LastDate]-@PassedParameter的函数,但错误发生了:

Operand data type date is invalid for subtract operator.

我不知道为什么?

hara是功能:

CREATE FUNCTION Salman( @Date  date )
RETURNS TABLE 
AS
RETURN 
(

SELECT TOP 1000 [ID]
      ,[Name]
      ,[LastDate]
      ,[Rule]
      ,[CoA]
  FROM [Scheduling_Employee].[dbo].[Group]
  where ([LastDate]-@Date)%[Rule]=0  
)
GO

3 个答案:

答案 0 :(得分:4)

您可以尝试使用DATEDIFF function

DATEDIFF ( datepart , startdate , enddate )

所以在你的情况下你可能会改变这样:

where DATEDIFF(dd,LastDate,@Date)%[Rule]=0
               ^^--Change this to mm,qq whatever you want.

答案 1 :(得分:0)

试试这个:

CREATE FUNCTION Salman( @Date  date )
RETURNS TABLE 
AS
RETURN 
(

SELECT TOP 1000 [ID]
  ,[Name]
  ,[LastDate]
  ,[Rule]
  ,[CoA]
FROM [Scheduling_Employee].[dbo].[Group]
where (Datediff(dd,[LastDate],@Date))%[Rule]=0  
)
GO

答案 2 :(得分:0)

我相信您两个日期的格式并不完全相同。这应该起作用。

CREATE FUNCTION Salman( @Date  date )
RETURNS TABLE 
AS
RETURN 
(

SELECT TOP 1000 [ID]
      ,[Name]
      ,[LastDate]
      ,[Rule]
      ,[CoA]
  FROM [Scheduling_Employee].[dbo].[Group]
  where (cast([LastDate] as datetime)-cast(@Date as datetime))%[Rule]=0  
)
GO