数据类型与自定义函数生成的整数上的数学运算符不匹配

data type mismatch with mathematical operators on integer generated by custom function

我正在尝试 运行 在 MS Access 上进行一个非常简单的 select 查询,该查询调用其他人创建的自定义函数。函数 returns 是一个整数,但是当我尝试使用简单的运算符应用条件时,我被告知数据类型不匹配。令人沮丧的是,就在我收到此消息并且值全部替换为“#NAME?”之前,我看到已返回正确的信息。谁能指出我哪里出错了?

查询是:

SELECT p.nhs_number, age(p.date_of_birth) AS age
FROM patient_tbl AS p
WHERE (((age(p.date_of_birth))<16));

函数是:

' Returns the difference in full years from DateOfBirth to current date,
' optionally to another date.
' Returns zero if AnotherDate is earlier than DateOfBirth.
'
' Calculates correctly for:
'   leap years
'   dates of 29. February
'   date/time values with embedded time values
'   any date/time value of data type Date
'
' DateAdd() is used for check for month end of February as it correctly
' returns Feb. 28th when adding a count of years to dates of Feb. 29th
' when the resulting year is a common year.
'
' 2015-11-24. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function Age( _
ByVal DateOfBirth As Date, _
Optional ByVal AnotherDate As Variant) _
As Integer

Dim ThisDate    As Date
Dim Years       As Integer
 
If IsDate(AnotherDate) Then
    ThisDate = CDate(AnotherDate)
Else
    ThisDate = Date
End If

' Find difference in calendar years.
Years = DateDiff("yyyy", DateOfBirth, ThisDate)
If Years > 0 Then
    ' Decrease by 1 if current date is earlier than birthday of current year
    ' using DateDiff to ignore a time portion of DateOfBirth.
    If DateDiff("d", ThisDate, DateAdd("yyyy", Years, DateOfBirth)) > 0 Then
        Years = Years - 1
    End If
ElseIf Years < 0 Then
    Years = 0
End If

Age = Years
 
End Function

谢谢!

您可能有一些 Null 值。

尝试排除这些:

SELECT p.nhs_number, age(p.date_of_birth) AS age
FROM patient_tbl AS p
WHERE (p.date_of_birth Is Not Null) And (age(p.date_of_birth)<16);

或替换为:

SELECT p.nhs_number, age(Nz(p.date_of_birth, Date())) AS age
FROM patient_tbl AS p
WHERE age(Nz(p.date_of_birth, Date()))<16;