9

我在 MS Access 中编写了一个 SQL 查询

select NVL(count(re.rule_status),0) from validation_result re, validation_rules ru where re.cycle_nbr="+cycle_nbr+" and re.rule_response=ru.rule_desc and re.rule_status='FAIL' and ru.rule_category='NAMING_CONVENTION' group by re.rule_status"

但输出是Null. 我想将其转换为Zero. 如果我使用NVL函数,则 MS Access 不接受它。我也尝试NZ了函数,但它也给出了相同的输出,即 NULL 而不是零。

4

1 回答 1

10

Nz()绝对是您正在寻找的功能。你说你试过了,它回来了Null,但我觉得这很难相信,因为重点Nz()回来Null。以供参考:

x = Nz(Null, 0)返回 0 ( VbVarType.vbInteger)

x = Nz(Null, "")返回一个空字符串 ( VbVarType.vbString)

x = Nz(Null)返回一个空变量 ( VbVarType.vbEmpty, not VbVarType.vbNull )

编辑

进一步调查表明,在您的特定情况下,问题是您正在执行COUNT(re.rule_status)的查询中也执行了GROUP BY re.rule_status. 如果WHERE查询的子句导致一个空集(不返回任何行),那么整个查询只是不返回任何行,而不是返回值为 0 或 Null 的单行。

这可以通过以下测试代码进行验证...

Sub NzTest()
Dim rst As DAO.Recordset, strSQL As String
strSQL = "SELECT Nz(COUNT(LastName), 0) FROM Members WHERE False GROUP BY LastName"
Debug.Print strSQL
Set rst = CurrentDb.OpenRecordset(strSQL, dbOpenSnapshot)
If rst.EOF Then
    Debug.Print "No rows were returned."
Else
    Debug.Print "Count = " & rst(0).Value
End If
rst.Close
Set rst = Nothing
End Sub

...产生结果

SELECT Nz(COUNT(LastName), 0) FROM Members WHERE False GROUP BY LastName
No rows were returned.

删除后,GROUP BY我们得到...

SELECT Nz(COUNT(LastName), 0) FROM Members WHERE False
Count = 0

...实际上Nz()在这种情况下甚至不需要:

SELECT COUNT(LastName) FROM Members WHERE False
Count = 0
于 2013-05-30T08:10:31.203 回答