在访问数据库中将Null转换为零

时间:2011-01-16 14:01:03

标签: vb.net ms-access oledb

考虑到 Grade.firstExam,Grade.secondExam, Grade.finalExam 都是TEXT且不是数字,我无法获得将空值转换为零的确切解决方案。我已经尝试使用NZ()但它返回一条错误消息(表达式中的未定义函数'NZ') 我使用VB.net与MS Access作为我的数据库。我还导入了 System.Data.OleDb 命名空间。

    SQLStatement = " SELECT     Student.idNumber as 'IDno', "
    SQLStatement &= "           Student.lastName + ', ' + Student.firstName as 'FullName', "
    SQLStatement &= "           Grade.firstExam as 'firstExam', "
    SQLStatement &= "           Grade.secondExam as 'secondExam', "
    SQLStatement &= "           Grade.finalExam as 'finalExam', "
    SQLStatement &= "           ((CDBL(Grade.firstExam) + CDBL(Grade.secondExam) + CDBL(Grade.finalExam) + CDBL(Grade.finalExam)) / 4) as 'Average' "
    sqlstatement &= "FROM       Student LEFT OUTER JOIN Grade ON "
    sqlstatement &= "           Student.idNumber = Grade.idNumber "
    sqlstatement &= "WHERE      Student.idNumber = '" & StudentID & "' "
    SQLStatement &= "ORDER BY   ((CDBL(Grade.firstExam) + CDBL(Grade.secondExam) + CDBL(Grade.finalExam) + CDBL(Grade.finalExam)) / 4) DESC"

如何转换字段中存在的空字符串或null?

2 个答案:

答案 0 :(得分:3)

在你的SQL中尝试这样的事情:

SQLStatement &= "          IIf(IsNull(Grade.firstExam),'0',Grade.firstExam) as 'firstExam', "

答案 1 :(得分:3)

您收到此消息错误可能是因为您正在使用SQL请求中的VB函数:

mySQLRequest = "SELECT ..., NZ(yourNumber,0), ..."

数据库引擎无法理解NZ函数

你应该这样写下你的要求:

mySQLRequest = "SELECT ..., IIf([myField] Is Null,0,[myField]) as myField, ..."